lc面试准备:Implement Stack using Queues
1 题目
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).
接口: 实现4个方法
2 思路
用2个queue
来实现,java
推荐用LinkedList
作为Queue
.
Version A: The stack should be efficient when pushing an item.
Version B: The stack should be efficient when popping an item.
Version A: push O(1); pop O(n)
push:
- enqueue in queue1
pop:
- while size of queue1 is bigger than 1, pipe dequeued items from queue1 into queue2
- dequeue and return the last item of queue1, then switch the names of queue1 and queue2
Version B: push O(n); pop O(1)
push:
- enqueue in queue2
- enqueue all items of queue1 in queue2, then switch the names of queue1 and queue2
pop:
- deqeue from queue1
3 代码
Vesion A
class MyStackVersionA {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
q1.add(x);
}
// Removes the element on top of the stack.
public void pop() {
top();
q1.poll();
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
// Get the top element.
public int top() {
int size = q1.size();
if (size > 1) {
int count = size - 1;
for (int i = 0; i < count; i++) {
q2.add(q1.poll());
}
}
return q1.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}
Vesion B
class MyStackVersionB {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
q2.add(x);
int size = q1.size();
for(int i = 0; i < size; i++) {
q2.add(q1.poll());
}
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
// Removes the element on top of the stack.
public void pop() {
q1.poll();
}
// Get the top element.
public int top() {
return q1.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}
4 总结
- 用两个
queue
实现stack
, pop 和 push的效率的选择。 - 由于题目假设
pop
和peek
都不会在队列为空的时候执行,避免了Null Pointer Exception
. - stack 和 queue的相互实现,很好的考察基本功。
5 参考
posted on 2015-07-07 19:42 BYRHuangQiang 阅读(348) 评论(0) 编辑 收藏 举报