題目
使用隊列實現棧的下列操做:spa
push(x) -- 元素 x 入棧 pop() -- 移除棧頂元素 top() -- 獲取棧頂元素 empty() -- 返回棧是否爲空 注意:code
你只能使用隊列的基本操做-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操做是合法的。 你所使用的語言也許不支持隊列。 你能夠使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操做便可。 你能夠假設全部操做都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操做)。隊列
思路
跟用棧實現隊列差很少,就是pop的時候,應該pop的是剛剛push進隊列的元素,爲了實現這一點,能夠在push以前,利用另外一個隊列,將當前隊列清空,而後push元素,再將另外一個隊列的元素push回來。element
代碼
class MyStack { private: queue<int> q1,q2; public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { while(!q2.empty()){ q1.push(q2.front()); q2.pop(); } q2.push(x); while(!q1.empty()){ q2.push(q1.front()); q1.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int a=q2.front(); q2.pop(); return a; } /** Get the top element. */ int top() { return q2.front(); } /** Returns whether the stack is empty. */ bool empty() { return q2.empty(); } }; /** * 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(); */ ```