java在已排序的LinkedList中添加元素
我有一个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
方法可以缩短很多。谢谢
共 (0) 个答案