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 //顺序栈结构定义 8 { 9 int *base; //栈底指针 10 int *top; //栈顶指针 11 int stacksize; //栈可使用的最大容量 12 } Sqstack; 13 14 //初始化,构造一个空栈 15 int Init_Stack(Sqstack &s) 16 { 17 s.base = new int[MAXSIZE]; //为顺序栈动态分配一个最大容量为MAXSIZE的数组空间 18 if(!s.base) exit(-1); //分配失败则退出 19 s.top = s.base; //top初始为base,表栈空 20 s.stacksize = MAXSIZE; 21 return 0; 22 } 23 24 //入栈操作 25 int Push_Stack(Sqstack &s, int e) 26 { 27 if(s.top - s.base == s.stacksize) //栈满退出 28 return 1; 29 *s.top++ = e; //将元素e压入栈顶,同时栈顶指针加1 30 //等同于*s.top=e;s.top++; 31 return 0; 32 } 33 34 //出栈操作 35 int Pop_Stack(Sqstack &s) 36 { 37 if(s.top == s.base) return 1; //栈空 38 --s.top; //栈顶指针减1 39 return 0; 40 } 41 42 //取栈顶元素 43 int Get_Top(Sqstack s) 44 { 45 if(s.top != s.base) //栈非空 46 return *(s.top - 1); //栈顶指针不变,返回栈顶元素的值 47 } 48 49 //输出栈 50 void printstack(Sqstack s) 51 { 52 while((s.top != s.base)) //栈非空 53 { 54 cout << Get_Top(s) << " "; 55 Pop_Stack(s); 56 } 57 cout << endl; 58 } 59 60 int main() 61 { 62 Sqstack s; 63 Init_Stack(s); 64 for (int i = 0; i < 10; ++i) 65 { 66 Push_Stack(s, i); 67 } 68 int a, b; 69 cout << "1--print,2--pop,3--push,0--exit "; 70 for(int i = 0; i < 4; ++i) 71 { 72 cin >> a; 73 if (a == 1) 74 { 75 printstack(s); 76 } 77 else if (a == 3) 78 { 79 cout << "元栈为:"; 80 printstack(s); 81 cout << "请输入要插入的数:"; 82 cin >> b; 83 Push_Stack(s, b); 84 cout << "插入后栈为:"; 85 printstack(s); 86 } 87 else if (a == 2) 88 { 89 cout << "元栈为:"; 90 printstack(s); 91 //cout<<"请输入要插入的数:"; 92 //cin>>b; 93 Pop_Stack(s); 94 cout << "pop后栈为:"; 95 printstack(s); 96 } 97 else if (a == 0) 98 { 99 return 0; 100 } 101 } 102 return 0; 103 }