简体   繁体   中英

LeetCode Merge sorted linked list -- how does this code work?

I'm working on the LeetCode problem: merge 2 sorted linked lists :

You are given the heads of two sorted linked lists list1 and list2 .

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:

  1. is ListNode() a kind of function? what does it do?
  2. does while list1 and list2 mean: if list1 and list2 is not blank?
  3. list1, cur=list1.next, list1 , is this supposed to mean that the entire list1 equals to the next value in list1 ? And the current node equals to the entire list1 ?
  4. does if list1 or list2: cur.next = list1 if list1 else list2 mean that if either list is empty, the next node will be the non empty list?
  5. for: return dummy.next , I thought you're supposed to return an entire merged linked list, isn't returning dummy.next just returning one node?

I'm new to linked lists

is ListNode() a kind of function? what does it do?

ListNode is a class. The template code that is presented to you has a comment block that has its definition:

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

With ListNode() the constructor ( __init__ ) is called. As no arguments are passed, the created node will have its val attribute set to 0 and its next attribute to None .

does while list1 and list2 mean: if list1 and list2 is not blank?

Since list1 and list2 are either instances of the ListNode class or are None , this condition checks that neither is None and the loop will repeat as long as that is the case. When at least one of them becomes None this condition will end the loop.

list1, cur=list1.next, list1 , is this supposed to mean that the entire list1 equals to the next value in list1 ? And the current node equals to the entire list1 ?

This is a tuple assignment, ie two assignments happen. You could write the following equivalent code:

cur = list1
list1 = list1.next

The assignment to cur means that cur now references the (first) node of list1 . The assignment to list1 means that it will reference the successor of that node. You could say that list1 now references a list that has one less node.

does this mean that if either list is empty, the next node will be the non empty list?

if list1 or list2 is executed after the loop. At that moment we know that at least list1 or list2 is None . This if checks if there is still one that is not None . If so, those nodes still need to be added to the merged result. And that is achieved with:

cur.next = list1 if list1 else list2

cur is always referencing the last node in the merged list. By assigning to cur.next we will append the remaining nodes to the merged list. The assigned value is either list1 or list2 whichever is the non-empty list. It could also have been written as:

cur.next = list1 or list2

return dummy.next , I thought you're supposed to return an entire merged linked list, isn't returning dummy.next just returning one node?

Initially, dummy.next is None , but as cur is initialised as a reference to that node and in the loop cur.next is assigned a node, we actually update that next attribute. Then the loop makes cur reference that node, and in a next iteration that node also gets a next ...etc, and so the merged list is being chained together.

You may also want to read Merging two linked lists - how does the dummy node get updated?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM