DEV Community

睡觉
睡觉

Posted on

Merge Two Link Lists | LeetCode Practice #6

Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. Both lists are sorted in non-decreasing order. Return the head of the merged linked list.

The linked list is implemented through the class ListNode, which has default attributes val = 0 and next = None. Note that the attribute next stores the next node as a whole rather than its index.

Python

####Sort as Whole (Runtime: 0ms, Memory: 12.5MB)
    #DECLARE ListNode: Class(val: 0, next: None)
    #DECLARE list1: ARRAY of ListNode
    #DECLARE list2: ARRAY of ListNode
class Solution(object):
    def mergeTwoLists(self, list1, list2):
        whole_link = ListNode(0)
        current = whole_link
        while list1 and list2:
            if list1.val < list2.val:
                current.next = list1
                list1 = list1.next
            else:
                current.next = list2
                list2 = list2.next
            current = current.next
        if list1:
            current.next = list1
        else:
            current.next = list2
        return whole_link.next
Enter fullscreen mode Exit fullscreen mode

Thoughts

I had a rough time with this question. I think the description on LeetCode was quite vague, especially for beginners like me. In the past, I always assumed that the "next" attribute stored an index and worked together with a list. However, it turns out that people simply stuff the whole thing in it.

Top comments (0)