拆分问题,借用解决方案。
decreasingList(List list) {
if list empty then return empty
List restSolution = decreasingList(list.next)
... list.first ... // What now
问问自己,拥有restSolution
和list.first
应该返回什么。
这使得计算机科学比数学更有趣:懒惰、只做一点、委派工作。
抱歉以为这是作业
static class List {
int value;
List next;
List(int value, List next) {
this.value = value;
this.next = next;
}
static List makeList(int... values) {
List list = null;
List tail = null;
for (int value: values) {
List node = new List(value, null);
if (tail == null) {
list = node;
} else {
tail.next = node;
}
tail = node;
}
return list;
}
@Override
public String toString() {
if (next == null) {
return String.valueOf(value);
}
return String.valueOf(value) + "-->" + next.toString();
}
}
static List decreasingList(List list) {
if (list == null) {
return null;
}
List rest = decreasingList(list.next);
if (rest != null && list.value < rest.value) {
return rest;
}
list.next = rest;
return list;
}
public static void main(String[] args) {
List list = List.makeList(2, 4, 2, 1, 3, 0);
System.out.println("List: " + list);
list = decreasingList(list);
System.out.println("Decreasing: " + list);
}
递归可能会被解决,就像您所做的那样:通过遍历下一个节点并将下一个节点更改为前一个节点来反转。然后在尾部返回。
static List decreasingList(List list) {
List prior = null;
while (list != null) {
List next = list.next;
list.next = prior;
prior = list;
list = next;
}
list = prior; // The reversed list.
prior = null;
while (list != null) {
List next = list.next;
list.next = prior;
if (prior == null || list.value > prior.value) {
prior = list;
}
list = next;
}
list = prior;
return list;
}