栈实现队列
使⽤栈实现队列的下列操作:
push(x) – 将⼀个元素放⼊队列的尾部。
pop() – 从队列⾸部移除元素。
peek() – 返回队列⾸部的元素。
empty() – 返回队列是否为空。
代码实现
#include<iostream>
#include<string>
#include<stack>
using namespace std;
//栈实现队列
class Myqueue
{
public:
//定义入栈和出栈
stack<int> stIn;
stack<int> stOut;
void push(int x){
stIn.push(x);
}
int pop()
{
//只有出栈为空的时候才导入入栈的元素
if(stOut.empty())
{
while(!stIn.empty())//全部导入
{
stOut.push(stIn.top());
stIn.pop();//出栈每导入一次,入栈就弹出一次
}
}
int res=stOut.top();//取出栈顶元素
stOut.pop();//弹出栈顶元素
return res;
}
int peek()
{
int res =this->pop();//this指针表示当对象使用peek函数时,对象可以调用公有接口pop()
stOut.push(res);//栈顶元素在上一步被弹出,需要把它再次压入,恢复原来的出栈状态
return res;
}
bool empty()
{
return stIn.empty()&&stOut.empty();
}
};
int main()
{
Myqueue queue1;
queue1.push(1);
queue1.push(2);
queue1.push(3);
queue1.peek();
cout<<queue1.peek()<<endl;
queue1.pop();
queue1.peek();
cout<<queue1.peek()<<endl;
queue1.empty();
cout<<queue1.empty()<<endl;
}
结果:
1
2
0
图解
pop()函数运行过程:最后实现的效果是数字1作为队列第一个进入的元素,也是队列中第一个弹出的元素,实现了队列“先进先出”的原则。peek()函数和pop类似,只不过没有把元素删除,利用pop()实现时,由于元素被弹出了,所以需要再次放进去。