I am fairly new to Python and I am a bit confused that how are the l1 and l2 in the second function merge(self,l1,l2) accessing to .val? If we did not declare l1 and l2 as ListNode in the parameter of the merge function then how does it know that l1 and l2 are nodes and access to .val?
If someone can explain the concept I would really appreciate it. TIA
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists or len(lists) == 0:
return None
while len(lists) > 1:
combinedList = []
for i in range(0, len(lists), 2):
l1 = lists[i]
l2 = lists[i+1] if (i+1) < len(lists) else None
combinedList.append(self.merge(l1,l2))
lists = combinedList
return lists[0]
def merge(self, l1, l2):
dummy = ListNode()
output = dummy
while l1 and l2:
if l1.val < l2.val:
output.next = l1
l1 = l1.next
else:
output.next = l2
l2 = l2.next
output = output.next
if l1:
output.next = l1
elif l2:
output.next = l2
return dummy.next