21.合并两个有序链表

难度:简单
题目描述:
21.合并两个有序链表_第1张图片
思路总结:迭代思路能想到,类似合并数组,但是递归方法就有点精彩了,需要细细品味。其中的边界条件缺一不可。
题解一:
第一版

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

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        #思路:有点像合并数组
        cur1 = l1
        cur2 = l2
        head = ListNode(0)
        res = head
        while cur1 and cur2:
            if cur1.val >= cur2.val:
                head.next = cur2
                cur2 = cur2.next
            else:
                head.next = cur1
                cur1 = cur1.next
            head = head.next
        if cur1:
            head.next = cur1
        else:
            head.next = cur2
        return res.next

题解一结果:
21.合并两个有序链表_第2张图片
题解二:(递归)

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        #思路:递归,属实精彩。
        if not l1:return l2
        elif not l2:return l1
        elif l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

题解二结果:
21.合并两个有序链表_第3张图片

你可能感兴趣的:(朱滕威的面试之路)