【发布时间】:2013-04-11 03:00:49
【问题描述】:
我有一个 ListElement 对象的 LinkedList,我想创建一个 recursive 方法来添加新节点,同时仍保留列表的排序顺序。
现在我有:
public static ListElement InsertList(ListElement head, ListElement newelem) {
if (head == null) {
head = newelem;
head.next = null;
}
else if (head.next == null) {
newelem.next = null;
head.next = newelem;
}
else if (head.value < newelem.value) {
newelem.next = head;
head = newelem;
}
else if (head.value >= newelem.value) {
head = head.next;
return InsertList(head, newelem);
}
return head;
}
我用代码多次调用它:
ListElement head = null;
ListElement elem;
// this block of code is repeated multiple times with values of 3, 8, 20, and 15
elem - new ListElement();
elem.value = 6;
head = InsertList( head, elem );
输出如下:
6
6 3
8 6 3
20 8 6 3
15 8 6 3
这个输出对于前三行是正确的,但之后就变得很奇怪了。谁能改进我的算法?我觉得InsertList 方法可以缩短很多。谢谢!
【问题讨论】:
-
我看到了 2 个问题:1)我认为您需要反转前 2 个 elseif,因为您没有涵盖 head.next 为空,但 newelem.value 大于 head 的情况。价值。 2)如果你不应该重新分配头部,你就是最终的。
标签: java recursion linked-list