您的位置:首页 > 产品设计 > UI/UE

[LeetCode] Implement Stack using Queues

2015-06-11 11:12 609 查看
Implement Stack using Queues

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 may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

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 -- which means only
push to back
,
pop from front
,
size
, and
is empty
operations are valid.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

水题。用两个队列来模拟。

class Stack {
private:
queue<int> que[2];
int cur = 0;

public:
// Push element x onto stack.
void push(int x) {
que[cur].push(x);
}

// Removes the element on top of the stack.
void pop(void) {
while (que[cur].size() > 1) {
que[1 - cur].push(que[cur].front());
que[cur].pop();
}
que[cur].pop();
cur = 1 - cur;
}

// Get the top element.
int top(void) {
while (que[cur].size() > 1) {
que[1 - cur].push(que[cur].front());
que[cur].pop();
}
int top = que[cur].front();
que[1 - cur].push(que[cur].front());
que[cur].pop();
cur = 1 - cur;
return top;
}

// Return whether the stack is empty.
bool empty(void) {
return que[cur].empty();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: