通过两个栈构造队列
import java.util.Stack;
public class QueueBy2Stacks<T> {
private Stack<T> stack1;
private Stack<T> stack2;
public QueueBy2Stacks() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void offer(T t) {
stack1.push(t);
}
public T poll() {
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.empty() ? null : stack2.pop();
}
public static void main(String[] args) {
QueueBy2Stacks<String> queueBy2Stacks = new QueueBy2Stacks<>();
queueBy2Stacks.offer("qqqqqqqqq");
queueBy2Stacks.offer("wwwwwww");
queueBy2Stacks.offer("eeeeee");
queueBy2Stacks.offer("ttttttt");
System.out.println(queueBy2Stacks.poll());
System.out.println(queueBy2Stacks.poll());
System.out.println(queueBy2Stacks.poll());
System.out.println(queueBy2Stacks.poll());
System.out.println(queueBy2Stacks.poll());
}
}
通过两个队列构造栈
import java.util.LinkedList;
import java.util.Queue;
public class StackBy2Queue<T> {
private Queue<T> queue1;
private Queue<T> queue2;
public StackBy2Queue() {
queue1 = new LinkedList<T>();
queue2 = new LinkedList<T>();
}
public void push(T t) {
if (queue1.isEmpty()) {
queue2.offer(t);
} else {
queue1.offer(t);
}
}
public T pop() {
if (queue1.isEmpty() && queue2.isEmpty()) {
return null;
}
if (queue1.isEmpty()) {
while (queue2.size() > 1) {
queue1.offer(queue2.poll());
}
return queue2.poll();
} else {
while (queue1.size() > 1) {
queue2.offer(queue1.poll());
}
return queue1.poll();
}
}
public static void main(String[] args) {
StackBy2Queue<String> stackBy2Queue = new StackBy2Queue<>();
stackBy2Queue.push("1111111111111");
stackBy2Queue.push("2222222222222");
stackBy2Queue.push("3333333333333");
stackBy2Queue.push("4444444444444");
System.out.println(stackBy2Queue.pop());
System.out.println(stackBy2Queue.pop());
System.out.println(stackBy2Queue.pop());
System.out.println(stackBy2Queue.pop());
System.out.println(stackBy2Queue.pop());
System.out.println(stackBy2Queue.pop());
}
}