I’m working on the LeetCode problem: merge 2 sorted linked lists:
You are given the heads of two sorted linked lists
list1andlist2.Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
I couldn’t solve it, so I looked at an answer that worked. I’d like to dissect it and learn:
class Solution:
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 # *****
The parts with asterisks are where I have questions:
- is
ListNode()a kind of function? what does it do? - does
while list1 and list2mean : iflist1 and list2is not blank? list1, cur=list1.next, list1, is this supposed to mean that the entirelist1equals to the next value inlist1? And the current node equals to the entirelist1?- does
if list1 or list2: cur.next = list1 if list1 else list2mean that if either list is empty, the next node will be the non empty list? - for :
return dummy.next, I thought you’re supposed to return an entire merged linked list, isn’t returningdummy.nextjust returning one node?
I’m new to linked lists