Search code examples
pythonmergelinked-listsingly-linked-list

Cycle when merging two ListNodes


This problem is from LeetCode

# Definition for singly-linked list.
# class ListNode
# def __init__(self, val=0, next=None):
#   self.val = val
#   self.next = next

In my solution, if I do the following, I get an error that a cycle has been found in the ListNode:

elif (l1.val<l2.val): 
   sol = ListNode
   sol.val = l1.val
   sol.next = Solution.mergeTwoLists(self, l1.next, l2)
   return sol

Alternatively, if I define sol differently - as the following - the solution works:

elif (l1.val<l2.val): 
   sol = ListNode (val = l1.val)
   sol.next = Solution.mergeTwoLists(self, l1.next, l2)
   return sol

The difference is in the way that sol is initially defined.

I realize there are many ways to correctly solve this problem. However, I don't understand the fundamental difference between the two pieces of code above, particularly why one creates a cycle and the other doesn't. I would appreciate any insight!


Solution

  • The issue is with this line:

    sol = ListNode
    

    You're not creating a new object of type ListNode, but instead creating a reference to the class definition itself. By adding the round brackets ListNode() you're instantiating this object. This let's you then interact with it by calling it's .val and .next properties.