用隊列來實現棧的如下操作。
push(x) —— 將元素x添加進棧
pop() —— 從棧頂移除元素
top() —— 返回棧頂元素
empty() —— 返回棧是否為空
注意:
你必須使用一個只有標准操作的隊列。
也就是說,只有push/pop/size/empty等操作是有效的。
隊列可能不被原生支持,這取決於你所用的語言。
只要你只是用queue的標准操作,你可以用list或者deque(double-ended queue)來模擬隊列。
你可以假設所有的操作都是有效的(例如,pop或peek操作不會被用在空棧上)。
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue
-- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively.
You may simulate a queue by using a list or deque (double-ended queue),
as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example,
no pop or top operations will be called on an empty stack).
對棧和隊列不清楚的話,可以先看這篇圖文介紹:【算法】7 分不清棧和隊列?一張圖給你完整體會
至於這道題目,有一道非常非常類似的題目。本題是用隊列來實現棧,下面這題是用棧來實現隊列,因為在上一篇中講解過,原理是一樣的,大家可以自己看看:LeetCode 232 Implement Queue using Stacks(用棧來實現隊列)(*)
class Stack {
public:
queue q, q2;
// Push element x onto stack.
void push(int x) {
q.push(x);
}
// Removes the element on top of the stack.
void pop() {
if (q.size() == 1) q.pop();
else {
while (q.size() > 1) {
q2.push(q.front());
q.pop();
}
q.pop();
while (q2.size() > 0) {
q.push(q2.front());
q2.pop();
}
}
}
// Get the top element.
int top() {
if (q.size() == 1) return q.front();
while (q.size() > 1) {
q2.push(q.front());
q.pop();
}
int temp = q.front();
q2.push(q.front());
q.pop();
while (q2.size() > 0) {
q.push(q2.front());
q2.pop();
}
return temp;
}
// Return whether the stack is empty.
bool empty() {
return q.empty();
}
};