C语言实现栈
对一个栈的简单操作:创建、判空、进栈、出栈,获取栈顶元素
InitStack(&S)
SatckEmpty(S)
Push(&S,&x)
Pop(&S,&x)
GetTop(S,&x)
DestoryStack(&S):将top指针置为-1即可(“&”表示引用)
#include <stdio.h>
typedef int ElemType;//将 ElemType声明成int类型
#define MaxSize 10 //定义栈中元素最大个数
typedef struct{//结构体
ElemType data[MaxSize];//存放栈中元素
int top; //栈顶指针
}SqStack;
//初始化栈
void InitStack(SqStack &S){
S.top=-1;
}
// 判断栈空
bool SatckEmpty(SqStack &S){
if(S.top==-1)
return true;//栈空
else
return false;//不空
}
//入栈
bool Push(SqStack &S,ElemType x){
if(S.top==MaxSize-1)//栈满报错
return false;
/**S.top=S.top+1;先指针加一
S.data[S.top]=x;再给指针指向的元素赋值**/
S.data[++S.top]=x;
return true;
}
//出栈
bool Pop(SqStack &S,ElemType &x){
if(S.top==-1)//栈空报错
return false;
x=S.data[S.top];//先取出栈顶元素
S.top=S.top-1;//栈顶指针减一
return true;
}
//读取栈顶元素
bool GetTop(SqStack S,ElemType &x){
if(S.top==-1)//栈空报错
return false;
x=S.data[S.top];
return true;
}
int main(){
SqStack S;//声明一个栈
InitStack(S);//初始化一个栈
ElemType i;
for(i=1;i<=10;i++) {// 循环入栈
Push(S,i);
}
// Push(&S,x);
//判断是否为空
if(SatckEmpty(S))
printf("栈为空\n");
else
printf("栈不为空\n");
ElemType p;
GetTop(S,p);//获取栈顶元素
printf("栈顶元素%d\n",p);
ElemType x;
for(i=1;i<=10;i++){//循环出栈
Pop(S,x);
printf("%d\n",x);
}
// Pop(&S,&x);
//判断此时栈为空
if(SatckEmpty(S))
printf("栈为空\n");
else
printf("栈不为空\n");
return 0;
}
运行结果:
栈不为空
栈顶元素10
10
9
8
7
6
5
4
3
2
1
栈为空