LeetCode 21. Merge Two Sorted Lists 解答

视频讲解

代码

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        
        # Solution -1 Iteration
        # # create dummy head
        # dummy_head = ListNode(0)
        # new_tail = dummy_head

        # # keep appending the lowest node to the tail
        # while l1 and l2:
        #     if l1.val > l2.val:

        #         new_tail.next = l2
        #         l2 = l2.next
                
        #     else:

        #         new_tail.next = l1
        #         l1 = l1.next
            
        #     new_tail = new_tail.next
        
        # # append unfinished list to the tail
        # new_tail.next = l1 if l1 else l2
        # return dummy_head.next


        # Solution-2: recursion

        # edge case
        if not l1:
            return l2
        if not l2:
            return l1
        
        # recursion relation.
        if l2.val <= l1.val:
            l1, l2 = l2, l1
            
        l1.next = self.mergeTwoLists(l1.next, l2)
        return l1

PPT讲解

本题涉及的知识点:

我的 Leetcode 讲解频道

代码链接

面试高频考点Youtube链接

面试低频考点Youtube链接

站内搜索 | Search


    视频 | Video Links

    Table of Contents