顺序栈
#include <iostream>
using namespace std;
const int StackSize=100;
template<class T>
struct Node {
T data;
Node* next;
};
template<class T>
class SeqStack
{
public:
SeqStack(){top=-1;}
~SeqStack(){}
void Push(T x);
T Pop();
T GetTop(){if(top!=-1) return data[top];}
int Empty(){if(top==-1)return 1;else return 0;}
private:
T data[StackSize];
int top;
};
template<class T>
void SeqStack<T>::Push(T x)
{
if(top==StackSize-1){throw "上溢";}
data[++top]=x;
}
template<class T>
T SeqStack<T>::Pop()
{
T x;
if(top==-1){throw "下溢";}
x=data[top--];
return x;
}
int main()
{
int x;
SeqStack<int> s;
s.Push(6);
s.Push(7);
s.Push(8);
s.Push(9);
s.Push(10);
cout<<"当前栈顶元素为:"<<s.GetTop()<<endl;
try
{
cout<<"请输入要入栈的元素"<<endl;
cin>>x;
s.Push(x);
}catch(const char *str){cout<<str<<endl;}
try
{
x=s.Pop();
cout<<"执行一次出栈操作,删除元素: "<<x<<endl;
}catch(const char *str){cout<<str<<endl;}
if(s.Empty())
{
cout<<"栈为空"<<endl;
}
else
{
cout<<"栈非空"<<endl;
}
return 0;
}
运行结果
![](https://img-blog.csdnimg.cn/direct/4cf473cf689a46ad9f7ec6de8aa68b91.png)
链栈
#include <iostream>
using namespace std;
template<class T>
struct Node {
T data;
Node* next;
};
template<class T>
class LinkStack
{
public:
LinkStack(){top=NULL;}
~LinkStack(){}
void Push(T x);
T Pop();
T GetTop(){if(top!=NULL)return top->data;}
bool Empty();
private:
Node<T> *top;
};
template<class T>
void LinkStack<T>::Push(T x)
{
Node<T> *pre;
pre=new Node<T>;
pre->data=x;
pre->next=top;
top=pre;
}
template<class T>
T LinkStack<T>::Pop()
{
Node<T> *pre=NULL;
T x;
if(top==NULL){throw "下溢";}
x=top->data;
pre=top;
top=top->next;
delete pre;
return x;
}
template<class T>
bool LinkStack<T>::Empty()
{
if(top==NULL)
{
return true;
}
else
{
return false;
}
}
int main()
{
int x;
LinkStack<int> ls;
ls.Push(6);
ls.Push(7);
ls.Push(8);
ls.Push(9);
ls.Push(10);
cout<<"当前栈顶元素为:"<<ls.GetTop()<<endl;
try
{
cout<<"请输入要入栈的元素"<<endl;
cin>>x;
ls.Push(x);
}catch(const char *str){cout<<str<<endl;}
cout<<"当前栈顶元素为:"<<ls.GetTop()<<endl;
try
{
x=ls.Pop();
cout<<"执行一次出栈操作,删除元素: "<<x<<endl;
}catch(const char *str){cout<<str<<endl;}
cout<<"当前栈顶元素为:"<<ls.GetTop()<<endl;
if(ls.Empty())
{
cout<<"栈为空"<<endl;
}
else
{
cout<<"栈非空"<<endl;
}
return 0;
}
运行结果
![](https://img-blog.csdnimg.cn/direct/cbdca7d1936848e2ad41aed18e49bff0.png)