顺序栈的基本操作
#include<stdio.h>
#include<malloc.h>
#define MAXSZIE 100
typedef int ElemType;
typedef struct SqStack{ElemType *top;ElemType *base;int sizestack;
}SqStack; //接口
SqStack *InitStack(SqStack &s)//初始化創建空棧
{s.base=(int*)malloc(sizeof(int)*MAXSZIE);if(!s.base)return 0;s.top=s.base;s.sizestack=MAXSZIE;return 0;
}
void pushStack(SqStack &s)//壓棧
{int e;scanf("%d",&e);if(s.top-s.base==s.sizestack) printf("內存已滿,無法繼續壓棧!");else*s.top++=e; //先壓棧,再使top指針上移
}
void DisplayStack(SqStack &s) //遍歷棧
{if(s.base==s.top)printf("棧空!");int *p;p=s.top;while(p>s.base){p--;printf("%d->",*p);}
}
int popStack(SqStack &s,ElemType &e) //出棧
{if(s.base==s.top){printf("棧已空!");}e=*(--s.top); //先使top指針下移,再彈棧; return e;
}
void CleanStack(SqStack &s)//清空棧
{if(s.base==s.top)printf("棧已空!");s.base=s.top;
}
void destory_stack(SqStack &s)//銷毀棧
{if(s.base){free(s.base);s.base=NULL;s.top=NULL;s.sizestack=0;}
}
int GetTop(SqStack s,ElemType &e) //得到棧頂元素,注意這里s前沒有添加引用,該處為值傳遞,不是引用傳遞,為了對main方法中的top指針不進行變動
{if(s.base==s.top)printf("棧已空!");e=*(--s.top);return e;
}
int StackEmpty(SqStack s)//判斷棧是否清空
{if(s.base==s.top)return 1;elsereturn 0;
}
int main()
{SqStack s;InitStack(s);int n;printf("你要輸入多少數據:");scanf("%d",&n);for(int i=1;i<=n;i++){printf("請輸入第%d個壓棧數據:",i);pushStack(s);}printf("該棧頂元素為:");int v;GetTop(s,v);printf("%d",v);printf("\n");int x,y;printf("請輸入出棧數據個數:");scanf("%d",&x);for(int i=1;i<=x;i++){popStack(s,y);printf("%d->",y);}printf("\n");printf("余下數據如下\n");DisplayStack(s);CleanStack(s);printf("\n清棧后,棧空否:%d(1:空 0:否)",StackEmpty(s));destory_stack(s);
}
總結
- 上一篇: 有关引用()的使用
- 下一篇: 链式队列的基本操作(入队、出队、遍历队列