栈的实现

来源:互联网 发布:mac管理员名称是什么 编辑:程序博客网 时间:2024/05/16 13:47
这里实现栈的基本的初始化,然后入栈出栈的操作,空栈满栈的判断,以及打印来验证。
<span style="font-size:14px;"></span>
<span style="font-size:14px;">#include<iostream> using namespace std; #define stacksize 100 typedef struct  {  int element[stacksize];  int top; }stack; stack *s;  stack *creatStack() {  int i=0;  s=new stack;  int x;  do  {cin>>x;  s->element[i]=x;  i++; }while(x!=0); //这儿不用i做判断,就是可以自己手动停止输入 s->top=i-2;  //这儿减2是因为每次输入之后,i自增1。输入0 结束时,i也多1,所以减2.return s;    }  bool empty(stack *S){ if(S->top==-1)  return true; //空 else  return false;}bool full(stack *S){  if(S->top==stacksize-1)   return true;  else   return false;}int getTop(stack *S){  return S->top;}bool push(stack *S,int x) {  if(S->top==stacksize-1)    //栈满。无法入栈 {  cout<<"栈满!"<<endl;  return false; } S->top++;  S->element[S->top]=x;  return true;  }  int pop(stack *S) {   int x; if(S->top==-1)  {  cout<<"栈为空!"<<endl; return false; }  else{   x=S->element[S->top];   S->top--;   return x; }  }  void print(stack *S) {  int i; for(i=0;i<=S->top;i++)   cout<<" "<<S->element[i]; cout<<endl; } int main()    //这部分偷懒的,直接拿了文库别人的main测试栈{  stack *L;  int e; int x,aa=1;  while(aa)  {   cout<<endl;     cout<<" 1.Creat stack"<<endl;      cout<<" 2.push stack"<<endl;      cout<<" 3.pop stack"<<endl;      cout<<" 4.Print stack"<<endl;      cout<<" 0.EXIT"<<endl;      cout<<endl;  cout<<"Please select mark!(1/2/3/4/0):";      cin>>x;      switch(x)   {      case 1: L=creatstack();break;       case 2: cout<<"Input the number! e=";               cin>>e;               push(L,e);break;       case 3: pop(L,&e);break;       case 4: print(L);break;       case 0: return 0;       default: aa=0;break;  }  }  }</span>


1 0
原创粉丝点击