/** * 两个队列模仿一个栈 * 第一种思路: * push 放进空的队列,然后把另一个队列的数据加到本队列后面 * pop remove非空队列头就好 * 第二种思路 * push 放入非空队列 * pop 时 将非空队列数据转移到空队列只保留最后一个并弹出 * * *
第一种思路代码:
static Deque<Integer> q1=new ArrayDeque<>(); //保存的弹出的顺序
static Deque<Integer> q2=new ArrayDeque<>();
public static void push(int x){
if (q2.isEmpty()) {
q2.add(x);
while (q1.size()>0) q2.add(q1.remove());
}
else if (q1.isEmpty()){
q1.add(x);
while (q2.size()>0) q1.add(q2.remove());
}
}
public static int pop(){
if (q1.isEmpty() && q2.isEmpty()) return -1;
if (!q2.isEmpty()) return q2.remove();
else if (!q1.isEmpty()) return q1.remove();
return -1;
}
第二种思路代码:
class Stack{
LinkedList<Integer> queue1 = new LinkedList<Integer>(); //队列1
LinkedList<Integer> queue2 = new LinkedList<Integer>(); //队列2
// Push element x onto stack.
public void push(int x) {
if(!queue2.isEmpty()){
queue2.offer(x);
}else{
queue1.offer(x);
}
}
// Removes the element on top of the stack.
public void pop() {
if(!empty()){
if(queue1.isEmpty()){
while(queue2.size() > 1){
queue1.offer(queue2.poll());
}
queue2.poll();
}else{
while(queue1.size() > 1){
queue2.offer(queue1.poll());
}
queue1.poll();
}
}
}
// Return whether the stack is empty.
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}
参考链接