[英]Adding an element in a sorted 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
方法可以缩短很多。 谢谢!
第四个条件块中的head = head.next
语句正在破坏head
元素。 我相信这应该是
else if(head.value >= newelem.value) {
head.next = InsertList(head.next, newelem);
}
当您尝试插入15时,您输入第四个条件:
// 20 > 15
else if (head.value >= newelem.value)
依次调用InsertList,但将8作为头节点传递,从而进入第3个条件:
// 8 < 15
else if (head.value < newelem.value)
在这里,你说
newelem.next = head;
设置15->下一个= 8
然后你说
head = newelem;
设置head = 15。
看到问题了吗? 使用@ Zim-Zam O'Pootertoot答案修复您的错误。
谢谢大家的帮助和解答!
我发现了另一条与我相似的帖子,其中的一个答案似乎对我有用。
这是任何希望看到的人的链接: https : //stackoverflow.com/a/15936744/1470257
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.