用栈实现一个队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为in类型。
输入描述
两行,第一行元素个数,第二行对应的元素(整型)
输出描述
按输入时的顺序输出各数据元素
样例输入
5
1 2 3 4 5
样例输出
1 2 3 4 5
提示
入队时,将node压入stack1 中
出队时,如果stack1不为空的话,将stack1的值弹出,压入stack2中,Stack2弹出的值为我们所需要的值
如果stack2不为空的话,将stack2的值弹出,压入stack1中
完整代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,e,i;
stack<int>a;
stack<int>b;
cin>>n;
for(i=0;i<n;i++)
{
cin>>m;
a.push(m);
}
while(!a.empty())
{
e=a.top();
b.push(e);
a.pop();
}
while(!b.empty())
{
cout<<b.top()<<" ";
b.pop();
}
return 0;
}
完整代码(中规中矩版)
#include<bits/stdc++.h>
using namespace std;
//顺序栈定义
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100//顺序栈存储空间的初始分配量
typedef int Status;
typedef char SElemType;
typedef struct {
SElemType *base;//栈底指针
SElemType *top;//栈顶指针
int stacksize;//栈可用的最大容量
} SqStack;
Status InitStack(SqStack &S);
Status Push(SqStack &S, SElemType e);
Status Pop(SqStack &S, SElemType &e);
//算法3.1 顺序栈的初始化
Status Push(SqStack &S, SElemType e){
if(S.top-S.base==S.stacksize)
return ERROR;
*S.top++=e;
return OK;
}
Status Pop(SqStack &S, SElemType &e){
if(S.top==S.base)
return ERROR;
e=*--S.top;
return OK;
}
Status InitStack(SqStack &S) {
//构造一个空栈S
S.base = new SElemType[MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
if (!S.base)
exit(OVERFLOW); //存储分配失败
S.top = S.base; //top初始为base,空栈
S.stacksize = MAXSIZE; //stacksize置为栈的最大容量MAXSIZE
return OK;
}
int main() {
SqStack s,z;
int n,i;
SElemType x,t;
InitStack(s);
InitStack(z);
cin>>n;
for(i=0;i<n;i++)
{
cin>>x;
Push(s,x);
}
while (Pop(s, t))
{
Push(z,t);
}
while (Pop(z,t))
{
cout<<t<<" ";
}
return 0;
}
考点
栈和队列