1 #include <iostream> 2 using namespace std; 3 #define MAXSIZE 100 //链式栈存储空间初始分配大小 4 #define OK 1 //链栈通常用单链表表示,节点结构与单链表相同。 5 #define ERROR 0 6 #define OVERFLOW -1 7 typedef struct StackNode //链栈结构 8 { 9 int data; //节点数据 10 struct StackNode *next; //节点指针,指向下一个节点 11 }StackNode,*LinkStack; 12 13 //初始化,构造一个空栈 14 int InitStack(LinkStack &s) 15 { 16 s=NULL; //栈顶指针置空 17 return 0; 18 } 19 20 //入栈操作 21 int PushStack(LinkStack &s,int e) 22 { 23 LinkStack p = new StackNode; //生成新节点 24 p->data = e; //将新节点数据域置为e 25 p->next=s; //将新节点插入栈顶 26 s=p; //修改栈顶指针为p 27 return 0; 28 } 29 30 //出栈操作 31 int PopStack(LinkStack &s) 32 { 33 LinkStack p = new StackNode; 34 if(s==NULL) //栈空 35 return -1; 36 p = s; //用p临时保存栈顶空间,以备释放 37 s = s->next; //修改栈顶指针 38 delete p; //释放原栈顶元素的空间 39 return 0; 40 } 41 42 //取栈顶元素 43 int GetTop(LinkStack s) 44 { 45 if(s!=NULL) //栈非空 46 return s->data; //栈顶指针不变,返回栈顶元素的值 47 } 48 49 //输出栈 50 void printstack(LinkStack s) 51 { 52 while(s!=NULL) //栈非空 53 { 54 cout << GetTop(s) << " "; 55 s=s->next; //不要写成popstack(s),不然输出一次后就栈就空了, 56 //没法第二次输出。 57 } 58 cout << endl; 59 } 60 61 int main() 62 { 63 LinkStack s; 64 InitStack(s); 65 for (int i = 0; i < 10; ++i) 66 { 67 PushStack(s, i); 68 } 69 int a, b; 70 cout << "1--print,2--pop,3--push,0--exit "; 71 for(int i = 0; i < 4; ++i) 72 { 73 cin >> a; 74 if (a == 1) 75 { 76 printstack(s); 77 } 78 else if (a == 2) 79 { 80 cout << "元栈为:"; 81 printstack(s); 82 PopStack(s); 83 cout << "pop后栈为:"; 84 printstack(s); 85 } 86 else if (a == 3) 87 { 88 cout << "元栈为:"; 89 printstack(s); 90 cout << "请输入要插入的数:"; 91 cin >> b; 92 PushStack(s, b); 93 cout << "插入后栈为:"; 94 printstack(s); 95 } 96 else if (a == 0) 97 { 98 return 0; 99 } 100 } 101 return 0; 102 } 103