顺序栈的基本操作

来源:互联网 发布:胸痛中心数据填报平台 编辑:程序博客网 时间:2024/06/05 19:40

方法一:

#include<stdio.h>#include<malloc.h>#define Maxsize 100typedef int dataType;typedef struct{dataType data[Maxsize];int top;}SeqStack;//创建顺序栈SeqStack *createStack(){SeqStack *s = (SeqStack*)malloc(sizeof(SeqStack));s->top = -1;return s;} //判断栈空int empty(SeqStack *s){return s->top == -1;} //判断栈是否满int full(SeqStack *s){return s->top == Maxsize-1;} //进栈void push(SeqStack *s,dataType x){if(full(s))  exit(1);s->data[++s->top] = x;} //出栈void pop(SeqStack *s){if(empty(s)) exit(1);s->top--;} //取栈顶元素的值dataType top(SeqStack *s) {if(empty(s)) exit(1);return s->data[s->top];}//取栈的元素个数int num(SeqStack *s){return s->top+1;}//遍历整个栈 void outStack(SeqStack *s){for(int i=s->top;i>=0;i--){printf("%d ",s->data[i]);}} int main(){SeqStack *s = createStack();push(s,80);push(s,90);push(s,70);push(s,60);pop(s);printf("栈顶元素为:");printf("%d ",top(s));printf("\n");printf("当前栈的所有元素为:");outStack(s);}

方法二:

#include<stdio.h>#define MaxSize 50typedef int ElemType;//定义栈结构体typedef struct{ElemType data[MaxSize];int top;}SqStack;//初始化栈void InitStack(SqStack &S){S.top = -1;}//判断栈是否为空bool StackEmpty(SqStack S){if(S.top == -1)return true;  //栈为空elsereturn false;}//入栈bool Push(SqStack &S,ElemType x){if(S.top == MaxSize-1)return false;S.data[++S.top] = x;return true;}//出栈bool Pop(SqStack &S,ElemType x){if(S.top == -1)return false;x = S.data[S.top--];printf("%d\n",x);//为查看栈的出栈元素return true;}//获取栈顶元素bool GetTop(SqStack S,ElemType &x){if(S.top == -1)return false;x = S.data[S.top];printf("%d\n",x);//为查看栈的栈顶元素return true;}int main(){SqStack s;int m,x;InitStack(s);Push(s,3);Push(s,9);Push(s,17);Pop(s,x);m = StackEmpty(s);GetTop(s,x);printf("%d\n",m);}