C语言实现顺序栈:
1.栈定义
2. 初始化
3. 元素入栈
4. 元素出栈
5. 栈元素遍历
6. 栈清空
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAXSIZE 100
#define ElemType char
typedef struct{
ElemType data[100];
int top;
}stack;
//定义一个栈初始化方法
void initStack(stack *s){
s->top=-1;
}
//定义一个栈空检测方法
int isEmpty(stack *s){
if(s->top==-1){
return 1;
}
else
return 0;
}
//定义一个栈满检测方法
int isFull(stack *s){
if (s->top>=MAXSIZE)
return 1;
else
return 0;
}
//定义一个栈元素添加方法
void Add(stack *s,int m){
if (isFull(s)==1){
printf("进栈失败\n");
}
else{
s->top++;
s->data[s->top] = m;
printf("元素%d进栈成功\n",m);
}
}
//定义一个栈顶元素弹出方法
void Pop(stack *s){
if (isEmpty(s)==0){
printf("弹出栈顶元素:%d\n",s->data[s->top]);
s->top--;
}
else{
printf("栈为空,弹出非法");
}
}
//定义一个栈元素遍历打印方法 自上而下
void ShowStack(stack *s){
int n=s->top;
if (isEmpty(s)==1){
printf("栈为空\n");
}
else{
printf("栈元素为:");
while (n>=0){
if (n!=0){
printf("%d->",s->data[n]);
}
else{
printf("%d\n",s->data[n]);
}
n--;
}
}
}
//定义一个栈清空方法
void ClearStack(stack *s){
s->top=-1;
}
void main(){
stack s;
initStack(&s);
Add(&s,1);
Add(&s,2);
ShowStack(&s);
Pop(&s);
Pop(&s);
ShowStack(&s);
}