顺序栈的操作

来源:互联网 发布:反电信网络诈骗 编辑:程序博客网 时间:2024/06/11 18:58
#include <iostream>#include <stdlib.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10#define ERROR -1#define OK 1#define OVERFLOW -1using namespace std;typedef struct{    int *base;    int *top;    int stacksize;} SqStack;int InitStack(SqStack &S){    S.base=(int*)malloc(STACK_INIT_SIZE*(sizeof(int)));    if(!S.base) exit(OVERFLOW);    S.top=S.base;    S.stacksize=STACK_INIT_SIZE;    return OK;}int GetTop(SqStack S,int &e){    if(S.top==S.base)        return ERROR;    e=*(S.top-1);    return OK;}int Push(SqStack &S,int e){    if(S.top-S.base>=S.stacksize)    {        S.base=(int*)realloc(S.base,(S.stacksize+STACK_INIT_SIZE)*sizeof(int));        if(!S.base)            exit(OVERFLOW);        S.top=S.base+S.stacksize;        S.stacksize+=STACK_INIT_SIZE;    }    *S.top++=e;    return OK;}int Pop(SqStack &S, int &e){    if(S.top==S.base)        return ERROR;    e=*(--S.top);    return OK;}void ElemSqstack(SqStack S){    if(S.top==S.base)    {        cout<<"栈内没有元素!"<<endl;        return;    }    cout<<"栈内元素为:";    while(S.top!=S.base)    {        cout<<*(--S.top)<<" ";    }    cout<<endl;}int main(){    SqStack S;    InitStack(S);    cout<<"请输入压入元素个数:"<<endl;    int n;    cin>>n;    int a;    cout<<"请依次输入入栈元素:"<<endl;    for(int i=0; i<n; i++)    {        cin>>a;        Push(S,a);    }    ElemSqstack(S);    int chose;    cout<<"1. 入栈  2.出栈 3.取栈顶元素 4.退出"<<endl;    cin>>chose;    while(chose!=4)    {        if(chose==1)        {            //cout<<"入栈"<<endl;            int q;            cout<<"想要入栈的元素为:";            cin>>q;            Push(S,q);            ElemSqstack(S);        }        else if(chose==2)        {            int e;            //cout<<"pop()"<<Pop(S, e)<<endl;            //cout<<"出栈"<<endl;            if(S.top==S.base)            {                cout<<"栈已经为空,不能出栈!"<<endl;                cout<<endl;            }            else            {                Pop(S, e);                cout<<"出栈的元素为:"<<e<<endl;                ElemSqstack(S);                cout<<endl;            }        }        else if(chose==3)        {            int m;            if(GetTop(S,m)==-1)            {                cout<<"栈为空!"<<endl;                cout<<endl;            }            else            {                cout<<"栈顶元素:"<<m<<endl;                ElemSqstack(S);            }        }        else if(chose==4)            break;        else        {            cout<<"请重新选择!"<<endl;            // cout<<"1. 入栈  2.出栈  3.退出"<<endl;        }        cout<<"1. 入栈  2.出栈  3.取栈顶元素 4.退出"<<endl;        cin>>chose;    }    cout<<"结束"<<endl;    return 0;}
0 0