两个队列
思路:每次把元素push进q2,然后把q1的元素push进q2,再交换q1和q2。
比如 1 2, 那么第一次q2是1, q1为空,然后交换 q1是1,q2为空
第二次 q2push了2,现在是2,q1这时候是1,然后把q1push到q2,q2就变成了2 1,此时q1为空,然后再交换q1,q2,那么q1就是 2 1,q2是空
class MyStack {
Queue<Integer> q1;
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) {
// 先push进q2
q2.offer(x);
// 把q1的元素都push到q2
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
// 交换q1和q2
Queue<Integer> temp = q1;
q1 = q2;
q2 = 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 top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
一个队列
入栈操作时,首先获得入栈前的元素个数 n,然后将元素入队到队列,再将队列中的前 n 个元素(即除了新入栈的元素之外的全部元素)依次出队并入队到队列,此时队列的前端的元素即为新入栈的元素,且队列的前端和后端分别对应栈顶和栈底 比如1 2 3
1 队列 1
2
1 队列1->先让2入队 -> 1 2 -> 1出队再入队 -> 2 1
3
2
1 队列 2 1 -> 先让3入队 -> 2 1 3 - > 2 1出队再入队 -> 3 2 1
class MyStack {
Queue<Integer> q;
/** Initialize your data structure here. */
public MyStack() {
q = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
// 获得入栈前的元素n
int n = q.size();
q.offer(x);
// 出队再重新入队
for(int i = 0; i < n; i++){
q.offer(q.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.poll();
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}