栈的顺序存储结构.txt

来自「栈的顺序存储结构」· 文本 代码 · 共 76 行

TXT
76
字号
#include <cstdlib>
#include <iostream>
#include<stdlib.h>
using namespace std;
typedef int ElemType;
struct Stack{
       ElemType *stack;//存栈元素 
       int top;//存栈顶元素下标位置 
       int MaxSize;//存储栈的最大长度 
       };
void InitStack(Stack& S)//初始化栈为空 
      {S.MaxSize=10;
       S.stack=new ElemType[S.MaxSize];//动态分配存储空间 
       if(!S.stack){
           cerr<<"动态存储分配失败"<<endl;
           exit(1);
                   }
            S.top=-1;
      }
void Push(Stack& S,ElemType item)//元素进栈 
{
     if(S.top==S.MaxSize-1){
          int k=sizeof(ElemType);
          S.stack=(ElemType*)realloc(S.stack,2*S.MaxSize);
          S.MaxSize=2*S.MaxSize;
          }
          S.top++;
          S.stack[S.top]=item;
} 
ElemType Pop(Stack &S)//删除栈顶元素并返回 
{if(S.top==-1)
        {
        cerr<<"stack is empty!"<<endl;
        exit(1);
             }
        S.top--;
        return S.stack[S.top+1];
}
ElemType Peek(Stack& S)//读取栈顶元素的值 
{if(S.top==-1){
               cerr<<"Stack is empty"<<endl;
               exit(1);}
               return S.stack[S.top];
}
bool EmptyStack(Stack& S)//判断栈是否为空 
{
     return S.top==-1;
  }

void ClearStack(Stack& S)//清除栈中所有元素 
{           if(S.stack){
             delete []S.stack;
             S.stack=0;
             }
 S.top=-1;
 S.MaxSize=0;
}

int main(int argc, char *argv[])
{Stack s;
 InitStack(s);
 int a[8]={3,8,5,17,9,30,15,22};
 int i;
 for(i=0;i<8;i++) Push(s,a[i]);
 cout<<Pop(s); cout<<' '<<Pop(s)<<endl;
 Push(s,68);
 cout<<Peek(s);cout<<' '<<Pop(s)<<endl;
 while(!EmptyStack(s)) cout<<Pop(s)<<' ';
 cout<<endl;
 ClearStack(s);


    system("PAUSE");
    return EXIT_SUCCESS;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?