顺序栈

来源:互联网 发布:js引用js文件 编辑:程序博客网 时间:2024/03/29 03:53

 #define M 10
#define N 10
#include<iostream.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct{
 int *base;
 int *top;
 int stacksize;
}Sqstack;
int InitStack(Sqstack &s){
 s.base=(int *)malloc(M*sizeof(int));
 if(!s.base)exit(0);
 s.top=s.base;
 s.stacksize=M;
 return 1;
}
int PushStack(Sqstack &s,int &e){
 if(s.top-s.base>=s.stacksize){
  s.base=(int*)realloc(s.base,(s.stacksize+N)*sizeof(int));
  if(!s.base)exit(0);
  s.top=s.stacksize+s.base;
  s.stacksize+=N;
 }
 *s.top++=e;
 return 1;
}//push
int PopStack(Sqstack &s,int e){
 if(s.top==s.base)return 0;
 e=*--s.top;
 return true;
}//pop
int GetTop(Sqstack s,int &e){
 if(s.top==s.base)return 0;
 e=*(s.top-1);
 return e;
}
int StackEmpty(Sqstack s)
{
 if(s.base==s.top)return 1;
 else return 0;
}
int StackFull(Sqstack s)
{if(s.top-s.base>=s.stacksize)return 0;
else return 1;
}

void main(){
 Sqstack s;
 InitStack(s);
 int e;
 cout<<"请输入十个数:/n/n";
 for(int i=1;i<=10;i++){
  cin>>e;
 PushStack(s,e);
 cout<<e<<" ";
 }
 cout<<endl;
 cout<<endl;
    cout<<"栈顶元素为:"<<GetTop(s,e)<<endl;

 if (StackEmpty(s))
    cout<<"栈为空!"<<endl;
 else cout<<"栈非空!"<<endl;
    if(StackFull(s))
  cout<<"栈已满!"<<endl;
 else cout<<"栈未满!"<<endl;
}