一、题目描述
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.
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
二、题解
方法一:单队列
核心方法 push:
- 每次在添加元素 add 之前,先用 size 记录队列中的元素个数。
- x 添加到队尾后,把 x 的之前的 size 个元素从队头逐个添加到队尾。
class MyStack {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
int size = queue.size();
queue.add(x);
while (size-- > 0) {
Integer t = queue.poll();
queue.offer(t);
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
复杂度分析
- 时间复杂度: ,
方法二:双队列实现(有两种做法)
- Q1:Q1 中添加元素之前永远是空的,添加完 x 后,应该把 Q2 的元素全部移动到 Q1,然后再让 Q2 与 Q1 交换,可保证 x 添加到队头。
- Q2:实时存储元素。
class MyStack {
private Queue<Integer> Q1;
private Queue<Integer> Q2;
/** Initialize your data structure here. */
public MyStack() {
Q1 = new LinkedList<>();
Q2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
Q1.offer(x);
while (!Q2.isEmpty()) {
Q1.offer(Q2.poll());
}
Queue t = Q1;
Q1 = Q2;
Q2 = t;
}
public int pop() {
return Q2.poll();
}
/** Get the top element. */
public int top() {
return Q2.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return Q2.isEmpty();
}
}
复杂度分析
- 时间复杂度: ,
做法二
public void push(int x) {
Q1.add(x);
top = x;
}
// Removes the element on top of the stack.
public void pop() {
while (Q1.size() > 1) {
q2.add(Q1.remove());
}
q1.poll();
Queue<Integer> t= Q1;
Q1 = q2;
Q2 = t;
}
复杂度分析
- 时间复杂度: ,