题目地址:
https://leetcode.com/problems/implement-stack-using-queues/
用队列实现栈。思路是,push的时候就入队,并将队头的
个元素全offer到队尾;peek或者pop的时候直接poll队头。代码如下:
import java.util.ArrayDeque;
import java.util.Queue;
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new ArrayDeque<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
for (int i = 0; i < queue.size() - 1; i++) {
queue.offer(queue.poll());
}
}
/** 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();
}
}
时间复杂度:peek或pop: ,push: 。