Search code examples
c#linked-listsingly-linked-list

Infinite Loop when merging two sorted Linked List


I'm running into an issue where the last node in a linked list is replicated repeatedly.

  • Parameter List1 = [1,2,4]
  • Parameter List2 = [1,3,4]
  • Expected Result = [1,1,2,3,4,4]
  • Actual Result = [1,1,2,3,4,4,4,4,4,4,...]

Something happens in the final else statement before the return that duplicates the 4 multiple times and I can't figure out what it is. What is causing the the final node to behave like this? Is it a problem with my SinglyLinkedNode Class?

before current.next = list2 is executed the values are

  • current = [1,1,2,3,4]
  • list2 = [4]

after it is executed the values are

  • current = [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;
    }
}



Solution

  • I made a mistake when initializing the parameters because I had a list2 node point to a list1 node.