链表 21. 归并两个有序的链表 python

21. Merge Two Sorted Lists (Easy)

  • 链表问题可以考虑哑节点(相当于就是头结点,或者一个哨兵)。

    • 思路一:迭代
      需要三个指针,一个哑节点。哑节点的val值默认为-1.
      1. 比较l1和l2的大小,哑节点指向小的那个
      2. l1和l2中小的那个后移
      3. 在接着比较现在l1和l2中val的大小,重复1,2步骤直致结束。
  • 思路二:递归

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        cur = dummy_head = ListNode(-1)
        while l1 and l2:
            if l1.val > l2.val:
                cur.next = l2
                l2 = l2.next
                cur = cur.next
            else:
                cur.next = l1
                l1 = l1.next
                cur = cur.next
        
        if l1:
            cur.next = l1
        elif l2:
            cur.next = l2
        else: 
            cur.next = None
        return dummy_head.next
posted @ 2021-07-11 16:16  把悲伤留给自己zzy  阅读(51)  评论(0)    收藏  举报