So I'm struggling with how pointers work/are managed in Python. Specifically, I was working on a practice problem that takes in two sorted integer linked lists (min to max), and returns the merged, sorted linked list. I couldn't figure out how to do it after an hour of banging my head against the wall, so I found a solution online, specifically this:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
cur = dummy = ListNode()
while list1 and list2:
if list1.val < list2.val:
cur.next = list1
list1, cur = list1.next, list1
else:
cur.next = list2
list2, cur = list2.next, list2
if list1 or list2:
cur.next = list1 if list1 else list2
return dummy.next
I understand the main idea: check the value of the current nodes against each other, put the smaller one into the list and move that input list forward one node, then repeat. However, I'm struggling with cur and dummy, and how they work within this solution:
Why does
dummy.nextlink tocur? The entire function seems to only concerncur, and there's no explicit moving of the pointer ofdummyto the head ofcurlike one would have to do in a language like C. I assume it has something to do with the fact that they're both initialized at the same time, but I don't quite understand how?Why do we update
curtwice in consecutive lines? First we setcur.nextequal to one of the lists, but then we setcuritself equal to that same list in the very next line? I don't understand why that is necessary, or even what it does in the construction of the linked list.
dummyshould really be calledheadorpre_heador something like that. Mutatingcur.nextis something entirely different to changingcuritself.