C++库里面的stack哟:
栈的链式实现:
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
int e;
typedef struct StackNode{
int data;
struct StackNode *next;
}StackNode,*LinkStack;
bool InitStack(LinkStack &S){ //初始化
S=NULL;
return true;
return false;
}
bool Push(LinkStack &S,int e){ //入栈
StackNode *p;
p=new StackNode;
p->data=e;
p->next=S;
S=p;
return true;
}
bool Pop(LinkStack &S,int &e){ //弹出
if(S==NULL) return false;
StackNode *p;
e=S->data;
p=S;
S=S->next;
delete p;
return true;
}
int GetTop(LinkStack S){ //取栈顶元素
if(S!=NULL){
return S->data;
}
}
bool StackEmpty(LinkStack S){ //判空
if(S==NULL)
return true;
return false;
}
void Show(LinkStack S){
if(S==NULL){
cout<<"栈空"<<endl;
}
else
cout<<"所有元素出栈结果如下"<<endl;
while(!StackEmpty(S)){
cout<<GetTop(S)<<" ";
Pop(S,e);
}
}
void menu(){
getchar();
getchar();
system("cls");
cout<<"请选择0~6"<<endl;
cout<<"0 : 初始化链栈"<<endl;
cout<<"1 : 元素入栈"<<endl;
cout<<"2 : 元素出栈"<<endl;
cout<<"3 : 取栈顶元素"<<endl;
cout<<"4 : 所有元素按顺序出栈"<<endl;
cout<<"5 : 销毁栈"<<endl;
cout<<"6 : 退出"<<endl;
}
int main(){
int choose;
cout<<"请选择0~6"<<endl;
cout<<"0 : 初始化链栈"<<endl;
cout<<"1 : 元素入栈"<<endl;
cout<<"2 : 元素出栈"<<endl;
cout<<"3 : 取栈顶元素"<<endl;
cout<<"4 : 所有元素按顺序出栈"<<endl;
cout<<"5 : 销毁栈"<<endl;
cout<<"6 : 退出"<<endl;
StackNode *S=NULL;
int off=0;
while(cin>>choose){
switch(choose){
case 0:{
if(InitStack(S)){
cout<<"初始化成功"<<endl;
}
else
cout<<"初始化失败"<<endl;
menu();
continue;
}
case 1:{
if(!InitStack(S)){
cout<<"栈还未初始化"<<endl;
}
else {
int num;
puts("请输入要入栈的数据,按Crtl+Z停止输入");
while(scanf("%d",&num)!=EOF){
Push(S,num);
}
puts("输入完毕");
}
menu();
continue;
}
case 2:{
if(StackEmpty(S)){
cout<<"栈为空"<<endl;
}
else {
cout<<GetTop(S)<<"出栈";
Pop(S,e);
cout<<"栈内剩余元素"<<endl;
if(S!=NULL)
Show(S);
else
cout<<"栈空"<<endl;
}
menu();
continue;
}
case 3:{
if(StackEmpty(S)){
cout<<"栈为空"<<endl;
}
else {
cout<<"栈顶元素为"<<GetTop(S)<<endl;
}
menu();
continue;
}
case 4:{
if(S!=NULL)
Show(S);
else
cout<<"栈空"<<endl;
menu();
continue;
}
case 5:{
delete S;
cout<<"销毁成功"<<endl;
menu();
continue;
}
case 6:{
cout<<"退出成功"<<endl;
off=1;
break;
}
default :{
cout<<"无此选项,请重新选择"<<endl;
menu();
continue;
}
}
if(off==1)
break;
}
return 0;
}