方法一: 用两个队列来回poll和offer实现: 压入栈O(1)、弹出栈O(n)
class MyStack {
private Queue<Integer> q1, q2;
int top; // 记录栈的栈顶元素,其实就是队列的尾
/** Initialize your data structure here. */
public MyStack() {
this.q1 = new LinkedList<Integer>();
this.q2 = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.offer(x);
top = x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while (q1.size() > 1) {
int a = q1.poll();
q2.offer(a); // 把q1中的元素依此添加到q2
top = a;
}
int curr = q1.poll(); // 当前pop出来的栈顶元素(队列的队尾元素))
Queue<Integer> temp = q2;
q2 = q1;
q1 = temp;
return curr;
}
/** Get the top element. */
public int peek() {
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.size() == 0;
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
方法二: 用两个队列来回poll和offer实现: 压入栈O(n)、弹出栈O(1)
class MyStack {
// 两个队列, 入栈时O(n)、出栈时O(1)
Queue<Integer> q1, 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存数据, q2做push的时候接数据的temp
q2.offer(x); // 把新元素放到队列的最底下
while (!q1.isEmpty()) {
q2.offer(q1.poll());
}
Queue temp = q2;
q2 = q1;
q1 = temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}
/** Get the top element. */
public int peek() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
方法三: 每次入队都把队尾之前的元素重新移到后边,造成队内顺序永远是实际入队顺序的逆序:插入1是1;插入2从1-2变成了2-1;插入3从2-1-3变成了3-2-1,顺序入队,逆序存储,达到后进先出的效果。
class MyStack {
// 一个队列实现的。push的时候滚一圈
Queue<Integer> q1;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.offer(x); //先直接加进去
int size = q1.size();
while (size-- > 1) { //执行size-1次操作,把底下的挪上去
q1.offer(q1.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}
/** Get the top element. */
public int peek() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/