栈的基本操作-数据结构

来源:互联网 发布:俄罗斯交友软件vk 编辑:程序博客网 时间:2024/06/05 03:17

栈的基本操作,顺序表动态存储。

基本操作:栈初始化,入栈,出栈,取栈顶元素,判断是否是空栈,清空栈。

例代码:

#include<stdio.h>#include<string.h>#include<malloc.h>#define Initsize 100#define Increase 100#define ERROR 0#define OK 1#define OVERFLOW -1typedef int Status;typedef int Elemtype;typedef struct SqStack{Elemtype *base,*top;int stacksize;}SqStack;//init stackStatus InitStack(SqStack &s){s.base=(Elemtype*)malloc(Initsize*sizeof(Elemtype));if(!s.base) return ERROR; s.top=s.base;s.stacksize=Initsize;return OK;}//push stackStatus Pushstack(SqStack &s,Elemtype e){Elemtype *temp;if(s.top-s.base+1>=s.stacksize)//stack full{temp=(Elemtype*)realloc(temp,(Increase+s.stacksize)*sizeof(Elemtype)); if(!temp) return ERROR;s.base=temp;s.top=s.base+s.stacksize;  //remalloc changes the s.top's address,relocate s.top pointers.stacksize+=Increase; }    *s.top=e;s.top++;return OK;}//stack if emptybool EmptyStack(SqStack s){if(s.base==s.top) return true;else return false;}//print stackStatus DisplayStack(SqStack s){if(EmptyStack(s)) printf("Stack is empty!\n");else{while(s.top!=s.base){s.top--;printf("%d ",*s.top);}printf("\n");}return OK;}//top elem pop stack Status PopStackelem(SqStack &s){if(EmptyStack(s)){printf("Stack is empty!\n");return ERROR;}s.top--;return OK;}  //get top elemElemtype GetStacktop(SqStack s,Elemtype &e){if(EmptyStack(s)){printf("Stack is empty!\n");return ERROR;} s.top--;e=*s.top;return OK;}Status ClearStack(SqStack &s){s.top=s.base;s.stacksize=0;return OK;}int main(){SqStack stack;int n,i;Elemtype e;InitStack(stack);printf("Input n and the num:");scanf("%d",&n);for(i=0;i<n;i++){scanf("%d",&e);Pushstack(stack,e);}DisplayStack(stack);  //print stackGetStacktop(stack,e); //get topif(e) printf("The top elem of stack is %d.\n",e);PopStackelem(stack); //pop stackGetStacktop(stack,e);//get topif(e) printf("The top elem of stack is %d.\n",e);DisplayStack(stack);ClearStack(stack);  //clear stack DisplayStack(stack);return 0;}


0 0