232.用栈实现队列
原题链接:232.用栈实现队列
思路
主要是要注意栈和队列的数据结构的区别,一个是后进先出, 一个是先进先出
如果要用栈模拟队列的先进先出,那就得使用另一个辅助空间来存储栈的栈顶元素,然后把栈最底部的元素弹出,再将存储栈里面的元素重新倒回原本的栈中
全代码:
class MyQueue {
public:MyQueue() {}void push(int x) {// 将元素 x 推到队列的末尾stacka.push(x);}int pop() {//从队列的开头移除并返回元素if (stacka.empty()){return NULL;}while (!stacka.empty()){stackb.push(stacka.top());stacka.pop();}int a = stackb.top();stackb.pop();while (!stackb.empty()){stacka.push(stackb.top());stackb.pop();}return a;}int peek() {//返回列表开头的元素if(stacka.empty()){return NULL;}while(!stacka.empty()){//把栈A的元素都压入栈B中进行存储stackb.push(stacka.top());stacka.pop();}int a = stackb.top();while (!stackb.empty()){//把栈b的元素都压回栈A中stacka.push(stackb.top());stackb.pop();}return a;}bool empty() {//判断队列是否为空,返回true,否则返回falseif (stacka.empty()){return true;}else{return false;}}
private:stack<int> stacka;stack<int> stackb;
};