我认为递归是最巧妙的:
public class Queue<E> {
private Stack<E> stack;
public Queue(Stack stack) {
this.stack = stack;
}
public E front() {
return Stack.top(stack);
}
public Queue<E> enqueue(E newValue) {
if (Stack.top(stack) == null) {
return new Queue(Stack.push(Stack.create(), newValue));
}
return new Queue<>(Stack.push(new Queue(Stack.pop(stack)).enqueue(newValue).stack, Stack.top(stack)));
}
public Queue<E> dequeue() {
return new Queue<>(Stack.pop(stack));
}
public String toString() {
return "Q: " + stack.toString();
}
}
请注意,不需要反转。
我认为 Stack 类中的某些代码对于“a”参数和额外变量有点不清楚,所以我对其进行了一些重构,并删除了所有未使用的内容。我还添加了一个toString(),它递归地遍历堆栈:
public class Stack<E> {
private final E value;
private final Stack<E> next;
private Stack(E value, Stack<E> next) {
this.value = value;
this.next = next;
}
public static <E> Stack<E> create() {
return new Stack<>(null, null);
}
public static <E> Stack<E> push(Stack<E> stack, E newValue) {
return new Stack<E>(newValue, stack);
}
public static <E> Stack<E> pop(Stack<E> stack) {
if (stack == null) {
return new Stack<E>(null, null);
} else if (stack.value == null) {
return new Stack<>(null, null);
} else if (stack.next == null) {
return new Stack<E>(null, null);
} else {
return stack.next;
}
}
public static <E> E top(Stack<E> stack) {
if (stack == null) {
return null;
} else if (stack.value == null) {
return null;
} else {
return stack.value;
}
}
public String toString() {
if (Stack.top(next) == null) {
return (value != null ? value.toString() : "Null");
}
return (value != null ? value.toString() : "Null") + " " + next.toString();
}
}
还有一点测试课。为了显示堆栈和队列之间的区别,它首先加载一个堆栈,然后将它传递给一个队列并添加更多元素,然后从前面拉一些:
public class QueueWithStackMain {
public static void main(String[] args) {
Stack<String> stack = Stack.create();
stack = Stack.push(stack, "1");
System.out.println(stack.toString());
stack = Stack.push(stack, "2");
System.out.println(stack.toString());
stack = Stack.push(stack, "3");
System.out.println(stack.toString());
Queue<String> queue = new Queue<>(stack);
System.out.println(queue.toString());
queue = queue.enqueue("4");
System.out.println(queue.toString());
queue = queue.enqueue("5");
System.out.println(queue.toString() + " -> " + queue.front());
queue = queue.dequeue();
System.out.println(queue.toString() + " -> " + queue.front());
}
}