C语言 顺序栈
代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define MaxSize 50 //定义栈中元素的最大个数 4 //顺序栈的定义 5 typedef struct{ 6 int data[MaxSize]; //静态数组存放栈中元素 7 int top; //栈顶指针 8 }SqStack; 9 10 //初始化栈 11 void InitStack(SqStack &S){ 12 S.top=-1; 13 } 14 15 //判断栈空 16 bool StackEmpty(SqStack S){ 17 if(S.top == -1) 18 return true; //栈空 19 else 20 return false; //栈不空 21 } 22 23 //新元素入栈 24 bool Push(SqStack &S,int x){ 25 if(S.top == MaxSize-1) //栈满,报错 26 return false; 27 S.data[++S.top] = x; //指针先加一,新元素后入栈 28 return true; 29 } 30 31 //出栈操作 32 bool Pop(SqStack &S,int &x){ 33 if(S.top == -1) //栈空,报错 34 return false; 35 x=S.data[S.top--]; //新元素先出栈,指针后减一 36 return true; 37 } 38 39 //读取栈顶元素 40 bool GetTop(SqStack S,int &x){ 41 if(S.top == -1) //栈空,报错 42 return false; 43 x=S.data[S.top]; //x记录栈顶元素 44 return true; 45 }