数据结构 栈和队列的操作 c++

    技术2024-10-05  53

    栈和队列的操作

    要求

    (1)编程实现栈的以下基本操作:建栈,取栈顶元素,入栈,出栈。

    (2)编程实现队列的以下基本操作:建队列,取队头元素,入队,出队。

    #include <iostream> #define OK 1 #define ERROR 0 #define MAXSIZE 100 typedef int SElemType; typedef int QElemType; typedef int Status; using namespace std; //栈 typedef struct{ SElemType *base; SElemType *top; int stacksize; }SqStack; //初始化 Status InitStack(SqStack &S) { S.base=new SElemType[MAXSIZE]; if(!S.base) { cout<<"存储分配失败"<<endl; return ERROR; } S.top = S.base; S.stacksize = MAXSIZE; return OK; } //入栈 Status Push(SqStack &S, SElemType e) { if(S.top-S.base==S.stacksize) { cout<<"栈满"<<endl; return ERROR; } *S.top++=e; //*S.top=e; //S.top++; return OK; } //出栈 Status Pop(SqStack &S, SElemType &e) { if(S.top==S.base) { cout<<"栈空"<<endl; return ERROR; } e=*--S.top; //--S.top; //e=*S.top; cout<<"出栈元素为:"<<e<<endl; return OK; } //取栈顶元素 Status GetTop(SqStack S, SElemType &e) { if(S.top==S.base) { cout<<"栈空"<<endl; return ERROR; } e=*(S.top-1); cout<<"栈顶元素为:"<<e<<endl; return OK; } //队列 typedef struct{ QElemType *base; int Front; int rear; }SqQueue; //创建队列 Status InitQueue(SqQueue &Q) { Q.base=new QElemType[MAXSIZE]; if(!Q.base) { cout<<"存储分配失败"<<endl; return ERROR; } Q.Front=Q.rear=0; return OK; } //入队 Status EnQueue(SqQueue &Q,QElemType e) { if((Q.rear+1)%MAXSIZE==Q.Front) { cout<<"队满"<<endl; return ERROR; } Q.base[Q.rear]=e; Q.rear=(Q.rear+1)%MAXSIZE; return OK; } //出队 Status DeQueue(SqQueue &Q,QElemType &e) { if(Q.Front==Q.rear) { cout<<"队空"<<endl; return ERROR; } e=Q.base[Q.Front]; Q.Front=(Q.Front+1)%MAXSIZE; cout<<"出队元素为:"<<e<<endl; return OK; } //取队头元素 Status GetHead(SqQueue Q,QElemType e) { if(Q.Front==Q.rear) { cout<<"队空"<<endl; return ERROR; } e=Q.base[Q.Front]; cout<<"队头元素为:"<<e<<endl; return OK; } int main() { cout << "1----入栈" << endl; cout << "2----出栈" << endl; cout << "3----取栈顶元素" << endl; cout << "4----入队" << endl; cout << "5----出队" << endl; cout << "6----取队头元素" << endl; cout << "退出,输入一个负数!" << endl; SqStack S; InitStack(S); SqQueue Q; InitQueue(Q); int i; bool flag=true; SElemType e; while(flag){ cout << "请输入一个操作码:"; cin>>i; if(i==1){ cout<<"请输入一个入栈元素:"; cin>>e; Push(S,e); } else if(i==2){ Pop(S,e); } else if(i==3){ GetTop(S,e); } else if(i==4){ cout<<"请输入一个入队元素:"; cin>>e; EnQueue(Q,e); } else if(i==5){ DeQueue(Q,e); } else if(i==6){ GetHead(Q,e); } else flag=false; } return 0; }
    Processed: 0.012, SQL: 9