[英]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.