栈作为数据结构很重要的一部分 不是很难 但是对于解决很多复杂问题有责非常重要的作用 栈的逻辑结构可以是顺序或者链序的 相对应的是数组实现和指针实现 在这里分别给出相应的源码,博主采用的是面向对象实现。
1.链栈
#include <iostream>
using namespace std;
class node{
public:
int data;
node* next;
};
class stack //该栈为带头结点的链栈
{
public:
stack();
~stack();
bool empty();
void pushstack(int );
void popstack();
void gettop();
void printstack();
private:
node* top;
protected:
};
stack::stack()
{
top->next=NULL;
}
stack::~stack()//析构函数 删除链栈
{
node* p=new node;
node* q=top->next;
while(q){
p=q;
q=q->next;
delete p;
}
}
bool stack::empty()//判空
{
if(top->next==NULL)
return true;
return false;
}
void stack::gettop()//打印栈顶元素
{
if(empty())
cout<<"empty stack"<<endl;
cout<<"top element is "<<top->next->data<<endl;
}
void stack::pushstack(int a)//压栈
{
node* p=new node;
p->data=a;
p->next=top->next;
top->next=p;
}
void stack::popstack() //弹栈
{
if(empty())
cout<<"empty stack!"<<endl;
node* q=top->next;
top->next=q->next;
}
void stack::printstack()
{
node* p=top->next;
while(p){
cout<<p->data;
p=p->next;
}
}
int main(int argc, char** argv) {
stack A;
int num;
cin>>num;
while(num!=-1) //键盘输入数据 -1为终止符
{
A.pushstack(num);
cin>>num;
}
A.printstack(); //打印栈中元素
return 0;
}
2.顺序栈
用数组实现
#define maxsize 100
#include <iostream>
using namespace std;
class stack
{
public:
stack();
~stack();
void pushstack(int) ;
void popstack();
bool is_empty();
bool is_full();
int gettop();
void printstack();
private:
int top;
int data[maxsize];
};
bool stack::is_empty()
{
if(top == -1)
return true;
return false;
}
bool stack::is_full()
{
if(top == maxsize-1)
return true;
return false;
}
void stack::pushstack(int a)
{
if(is_full()){
cout<<"full stack!"<<endl;
return;
}
data[++top]=a;
}
void stack::popstack()
{
if(is_empty()){
cout<<"empty stack!"<<endl;
return;
}
top--;
}
int stack::gettop()
{
if(is_empty())
return -1; //栈为空返回-1
return data[top];
}
void stack::printstack()
{
if(is_empty()){
cout<<"empty stack!"<<endl;
return;
}
for(int i=top;i>=0;){
cout<<data[top--];
}
}
int main()
{
stack A;
int num;
cin>>num;
while(num != -1){
A.pushstack(num);
cin>>num;
}
A.printstack();
return 1;
}