我有一个ListElement
对象的 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
方法可以缩短很多。谢谢!