我有一个ListElement
对象的LinkedList,我想创建一个递归的方法,该方法添加新的节点,同时仍然保留列表的排序顺序。在排序后的LinkedList中添加一个元素
现在我有:
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个elseifs其中head.next为空,但newelem.value大于head.value。 2)如果你不应该重新分配头部,那么你最后还是最后的。 – DMulligan 2013-04-11 03:10:56