使用队列实现栈的下列操作:
- push(x) -- 元素 x 入栈
- pop() -- 移除栈顶元素
- top() -- 获取栈顶元素
- empty() -- 返回栈是否为空
注意:
- 你只能使用队列的基本操作-- 也就是
push to back
,peek/pop from front
,size
, 和is empty
这些操作是合法的。 - 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
- 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
我是在做完学堂在线的一道题写出来的,不过也查到其他人有自己的做法。
其实没什么难度,大家根据代码中队列的操作同时结合几个具体的例子,就可以写出来了
算法分析:队列是先入先出,而栈是后入先出
所以用q1存储push进来的元素时,每当遇到pop操作,首先应该找到q1队列的队尾
要找到队尾元素只要q1不断pop就行,但是栈的pop函数不会返回弹出元素,所以需用front()先获取元素并存入q1队列中
然后保存q1队列的队尾同时pop
接着把q2的元素全部转移到q1中
记得此时把之前保存的q1的队尾元素返回
top函数类似
总的来说,q1存储所有元素,q2是在pop,top操作时临时存储弹出的队列元素的
-
class MyStack { public: queue<int> q1,q2; /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { q1.push(x); } /** Removes the element on top of the stack and returns that element. */ int pop() { while(q1.size() > 1){ q2.push(q1.front()); q1.pop(); } int tmp = q1.front(); q1.pop(); while(!q2.empty()){ q1.push(q2.front()); q2.pop(); } return tmp; } /** Get the top element. */ int top() { while(q1.size() > 1){ q2.push(q1.front()); q1.pop(); } int tmp = q1.front(); q1.pop(); while(!q2.empty()){ q1.push(q2.front()); q2.pop(); } q1.push(tmp); return tmp; } /** Returns whether the stack is empty. */ bool empty() { if(q1.empty()) return true; return false; } }; /** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * bool param_4 = obj.empty(); */