提问者:小点点

合并两个排序链表时的无限循环


我遇到了一个问题,即链表中的最后一个节点被重复复制。

  • 参数列表1=[1,2,4]
  • 参数列表2=[1,3,4]
  • 预期结果=[1,1,2,3,4,4]
  • 实际结果=[1,1,2,3,4,4,4,4,4,4,4,…]

在多次重复4的返回之前的最终else语句中发生了一些事情,我不知道它是什么。是什么导致了最终节点的行为是这样的?是我的SinglyLinkedNode类的问题吗?

在执行current.next=list2之前,值是

  • 当前=[1,1,2,3,4]
  • list2=[4]

执行后,值为

  • 电流=[1,1,2,3,4,4,4,4,4,4,…]
  • list2=[1,1,2,3,4,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;
    }
}



共2个答案

匿名用户

我在初始化参数时犯了一个错误,因为我有一个list2节点指向一个list1节点。

匿名用户

当您使用以下代码时,不要克隆对象,而是克隆对象的指针。在第2行中,导致current.next在赋值后引用到list1.next

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

但是您可以像这样更改代码。

1-更新您的对象公共类SinglyLinkedNode: IClone并实现此方法。

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;
}

在这里,我们有一个很好的例子