I am new to coding and am working on LeetCode#21 Merge two sorted list.
An example: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
A common solution to this question is:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
dummy = ListNode()
tail = dummy
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
if list1:
tail.next = list1
elif list2:
tail.next = list2
return dummy.next
I am confused with the last line: return dummy.next
Shouldn't it simply return the next node of dummy node? How will that return the whole list?