[英]Infinite Loop when merging two sorted Linked List
我遇到了一个问题,链表中的最后一个节点被重复复制。
在返回之前的最后一个 else 语句中发生了多次重复 4 的事情,我无法弄清楚它是什么。 是什么导致最终节点的行为如此? 我的 SingleLinkedNode 类有问题吗?
在current.next = list2
执行之前,值是
执行后的值为
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.