[英]Inserting into sorted linked list?
我对编码非常陌生,我无法理解代码中的错误,非常感谢您的帮助。
因此,除了最后一个元素外,代码都能正常工作,因为后面的元素为null,而我无法处理(我是非常新的)。
问题出在最后一部分。
public static void InsertingIntoSortedLinkedList(int value, int key)
{
Node m = new Node();
m.value=value;
m.key=key;
if (root==null)
{
m.Next = null;
root = m;
}
else
{
if (key<root.key)
{
m.Next = root;
root = m;
}
else
{
Node temp1 = root;
Node temp2 = null;
while ((temp1!=null)&&(temp1.key<key))
{
temp2 = temp1;
temp1 = temp1.Next;
}
if (temp1==null)
{
m.Next = null;
temp2.Next=m;
}
else
{
m.Next = temp1;
if (temp2!=null)//I either put this here and the last element is lost or I got a NullReferenceException. What should I change?
{
temp2.Next = m;
}
}
}
}
}
谢谢您的帮助。
您可能会发现问题的一种情况是,当您插入一个等于根值的值时,这些值将被跳过,因为您尝试在匹配项之前插入而不是更新根引用。
解决方案是在匹配值之后插入-这可以通过更改行来完成
while ((temp1!=null)&&(temp1.key<key))
至
while ((temp1 != null) && (temp1.key <= key))
或通过更改行在根元素处插入
if (key<root.key)
至
if (key <= root.key)
或在插入之前通过更新根值
if (temp2!=null)
{
temp2.Next = m;
}
else
root = m;
任何一项更改都应解决该问题
您有两种错别字:
if (key<root.key)
while ((temp1!=null)&&(temp1.key<key))
<key
末尾缺少>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.