#include<cstdlib> #include<iostream> #include<fstream> using namespace std; #define OK 1 #define ERROR 0 #define OVERFLOW -2 typedef int Status; typedef char SElemType; typedef struct StackNode{ SElemType data; struct StackNode *next; }StackNode,*LinkStack; //链栈的初始化 Status InitStack(LinkStack &S){ S=NULL; return OK; } //链栈的入栈 Status Push(LinkStack &S,SElemType e){ LinkStack p; p=new StackNode;//生成新结点 p->data=e;//将新节点数据域置为e p->next=S;//将新结点插入栈顶 S=p;//修改栈顶指针为p return OK; } //链栈的出栈 Status Pop(LinkStack &S,SElemType &e){ LinkStack p; if(S==NULL)return ERROR;//栈空 e=S->data; p=S; S=S->next;//修改栈顶指针 delete p;//释放原栈顶元素的空间 return OK; } //取链栈的栈顶元素 SElemType GetTop(LinkStack S){ if(S!=NULL)//栈非空 return S->data; } int main(){ LinkStack s; int choose,flag=0; SElemType j,t; cout<<" 1.初始化 "; cout<<" 2.入栈 "; cout<<" 3.读栈顶元素 "; cout<<" 4.出栈 "; cout<<" 0.退出 "; choose=-1; while(choose!=0){ cout<<" 请选择: "; cin>>choose; switch(choose){ case 1: if(InitStack(s)){ flag=1; cout<<" 成功对栈进行初始化 "; }else cout<<" 初始化栈失败 "; break; case 2:{ fstream file; file.open("SqStack.txt"); if(!file){ cout<<" 错误 为找到文件! "<<endl; flag=0; exit(ERROR); } if(flag){ flag=1; cout<<" 进栈元素依次为: "; while(!file.eof()){ file>>j; if(file.fail())break; else{ Push(s,j); cout<<j<<" "; } } cout<<endl<<endl; }else cout <<" 栈未建立,请重新选择 "; file.close(); } break; case 3: if(flag!=-1 && flag!=0) cout<<" 栈顶元素为 : "<<GetTop(s)<<endl<<endl; else cout<<" 栈中无元素,请重新选择 " <<endl; break; case 4: if(flag==1){ flag=0; cout<<" 依次弹出的栈顶元素为: "; while(Pop(s,t)) cout<<t<<" "; cout<<endl<<endl; }else cout <<" 栈未建立,请重新选择 "; break; } } return 0; }