【发布时间】:2021-09-03 09:21:36
【问题描述】:
我想实现一个反转堆栈的反转方法。我认为解决方案是递归。我尽力了,但它不起作用。谁能告诉我我的错误在哪里?
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 null;
}
public static <E> Stack<E> push(Stack<E> a, E e) {
Stack<E> erg = new Stack<E>(e,a);
return erg;
}
public static <E> Stack<E> pop(Stack<E> a) { //pop(push(s,e) = s
if (a == null) {
return Stack.<E>create();
}
else if (a.value == null){
return Stack.<E>create();
}
else {
return a.next;
}
}
public static <E> E top(Stack<E> a) {
if (a == null) {
return null;
}
else if (a.value == null){
return null;
}
else {
return a.value;
}
}
public static <E> boolean isEmpty(Stack<E> a) {
if (a == null) {
return true;
}
else if (a.value == null) {
return true;
}
else {
return false;
}
}
public static <E> Stack<E> reverse(Stack<E> s) {
Stack<E> top = Stack.<E>pop(s);
if (Stack.<E>isEmpty(s)) {
return top;
} else {
Stack<E> bottom = reverse(s);
Stack.<E>push(top, null);
return bottom;
}
}
}
我不允许使用 Java API 的类;我不允许添加更多的类或方法或属性。
【问题讨论】:
标签: java generics recursion linked-list stack