两个栈实现队列及两个队列实现栈:
两个栈实现队列:将一个栈内的数据倒到另一个栈里面,并弹出
两个队列实现栈:将一个队列里面的前(len-1)个数据添加到另一个队列,并弹出该队列的最后一个元素
public class Queue {
private static Stack<Integer> stack = new Stack<Integer>();
private static Stack<Integer> stack2 = new Stack<Integer>();
public static void main(String[] args) {
add(1);
add(2);
System.out.println(poll());
add(3);
System.out.println(poll());
}
private static void add(int value) {
stack.push(value);
}
private static Integer poll() {
if (stack.isEmpty()) {
try {
throw new Exception("queue is emtry");
} catch (Exception e) {
e.printStackTrace();
}
}
while (!stack.isEmpty()) {
stack2.push(stack.pop());
}
return stack2.pop();
}
}
public class Stack {
private static Queue<Integer> queue = new ArrayDeque<Integer>();
private static Queue<Integer> queue2 = new ArrayDeque<Integer>();
public static void main(String[] args) {
push(1);
push(2);
System.out.println(pop());
push(3);
push(4);
System.out.println(pop());
push(5);
System.out.println(pop());
}
public static void push(int value) {
while (queue.isEmpty()) {
queue2.add(value);
return;
}
while (queue2.isEmpty()) {
queue.add(value);
return;
}
}
public static Integer pop() {
if (queue.isEmpty() && queue2.isEmpty()) {
try {
throw new Exception("stack is emtry");
} catch (Exception e) {
e.printStackTrace();
}
}
if (queue2.isEmpty()) {
while (queue.size() > 1) {
queue2.add(queue.poll());
}
return queue.poll();
}
if (queue.isEmpty()) {
while (queue2.size() > 1) {
queue.add(queue2.poll());
}
return queue2.poll();
}
return null;
}
}