簡體   English   中英

合並兩個排序的鏈表時的無限循環

[英]Infinite Loop when merging two sorted Linked List

我遇到了一個問題,鏈表中的最后一個節點被重復復制。

  • 參數列表1 = [1,2,4]
  • 參數列表2 = [1,3,4]
  • 預期結果 = [1,1,2,3,4,4]
  • 實際結果 = [1,1,2,3,4,4,4,4,4,4,...]

在返回之前的最后一個 else 語句中發生了多次重復 4 的事情,我無法弄清楚它是什么。 是什么導致最終節點的行為如此? 我的 SingleLinkedNode 類有問題嗎?

current.next = list2執行之前,值是

  • 當前 = [1,1,2,3,4]
  • 列表2 = [4]

執行后的值為

  • 當前 = [1,1,2,3,4,4,4,4,4,..]
  • list2 = [1,1,2,3,4,4,4,4,4,...]
public static SinglyLinkedNode MergeTwoSortedLists(SinglyLinkedNode list1, SinglyLinkedNode list2)
{
    //if one list is null, return the other
    if (list1 == null) return list2;
    if (list2 == null) return list1;

    //declare the result node; declare the node that you will fill
    SinglyLinkedNode result = new SinglyLinkedNode();
    SinglyLinkedNode current = result;

    //while neither lists are empty
    while (list1 != null && list2 != null)
    {
        //do the comparisons and populate the current Node;
        if (list1.val <= list2.val)
        {
            current.next = list1;
            list1 = list1.next;
        }
        else
        {
            current.next = list2;
            list2 = list2.next;
        }
        current = current.next;
    }
    //when one list is empty, use the remaining list to fill the current node
    if (list1 != null)
    {
        current.next = list1;
    }
    else
    {
        current.next = list2;
    }
    
    return result.next;
}

public class SinglyLinkedNode
{
    public int val;
    public SinglyLinkedNode next;
    public SinglyLinkedNode(int val = 0, SinglyLinkedNode next = null)
    {
        this.val = val;
        this.next = next;
    }
}


我在初始化參數時犯了一個錯誤,因為我有一個 list2 節點指向一個 list1 節點。

一、必須重要的概念

當您使用以下代碼時,不要克隆對象,而是克隆對象的指針。 並在第 2 行導致current.next在分配后引用list1.next

 1- current.next = list1;
 2- list1 = list1.next;

但是你可以改變你的代碼。

1-更新您的對象public class SinglyLinkedNode : ICloneable並實現此方法。

public class SinglyLinkedNode : ICloneable
{
    // other code
    public object Clone()
    {
         return new SinglyLinkedNode(val, null);
    }
}

2 - 在此處更改

//when one list is empty, use the remaining list to fill the current node
if (list1 != null)
{
    current.next = list1;
    list1 = list1.next;
}
else
{
    current.next = list2;
    list2 = list2.next;
}

--- 這里,我們有一個很好的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM