繁体   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