题目链接:https://leetcode.com/problems/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 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).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
解题思路:
- 这道题很简单。建立两个队列,一个主队列(负责入队操作),一个辅助队列(负责颠倒队列顺序)。
- pop 和 top 操作时,如果主队列不为空,就把主队列中除最后一个元素外全部出队列,并进入辅助队列。
- 如果主队列为空,就把辅助队列除最后一个外全部出队列,并入队列到主队列中。当为 top操作时,获取辅助队列中最后一个元素的值后,还应当将其入队到主队列中。
- 必须保证,主队列中的最后一个元素一定是队列的末尾,以便满足每次将新元素入队时,保证所有元素的顺序不变。
注意:
LinkedList 既能模拟栈,又能模拟队列。但是二者在使用 API 时是有所区别的。
- 模拟栈时
- 入栈:push(),等同于 addFirst(E)
- 出栈:pop(),等同于 removeFirst()
- 获取栈顶元素:getFirst()
- 模拟队列时
- 入队列:offer()
- 出队列:poll()
- 获取队列第一个元素:peek()
class MyStack {
private LinkedList<Integer> myStack = null;
private LinkedList<Integer> myStack2 = null;
public MyStack() {
myStack = new LinkedList();
myStack2 = new LinkedList();
}
// Push element x onto stack.
public void push(int x) {
myStack.offer(x);
}
// Removes the element on top of the stack.
public void pop() {
if(!myStack.isEmpty()) {
while(myStack.size() != 1)
myStack2.offer(myStack.poll());
myStack.poll();
return;
} else {
while(myStack2.size() != 1)
myStack.offer(myStack2.poll());
myStack2.poll();
return;
}
}
// Get the top element.
public int top() {
if(!myStack.isEmpty()) {
while(myStack.size() != 1)
myStack2.offer(myStack.poll());
return myStack.peek();
} else {
while(myStack2.size() != 1)
myStack.offer(myStack2.poll());
int temp = myStack2.peek();
myStack.offer(myStack2.poll());
return temp;
}
}
// Return whether the stack is empty.
public boolean empty() {
if(myStack.isEmpty() && myStack2.isEmpty())
return true;
else
return false;
}
}
16 / 16 test cases passed.
Status: Accepted
Runtime: 168 ms