題目
使用隊列實現棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空
注意:
你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標准的隊列操作即可。
你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。
思路
跟用棧實現隊列差不多,就是pop的時候,應該pop的是剛剛push進隊列的元素,為了實現這一點,可以在push之前,利用另一個隊列,將當前隊列清空,然后push元素,再將另一個隊列的元素push回來。
代碼
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();
*/
```