剑指 Offer 25. 合并两个排序的链表 --递归与双指针解法

0 题目描述

leetcode原题链接:剑指 Offer 25. 合并两个排序的链表剑指 Offer 25. 合并两个排序的链表 --递归与双指针解法_第1张图片

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:
        cur = res = ListNode(0)
        while l1 and l2:
            if l1.val < l2.val:
                cur.next, l1 = l1, l1.next
            else:
                cur.next, l2 = l2, l2.next
            cur = cur.next
        cur.next = l1 if l1 else l2
        return res.next

2 递归解法

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 == None: return l2
        if l2 == None: return l1
        if l1.val < l2.val:
            mergedhead = l1
            mergedhead.next = self.mergeTwoLists(l1.next, l2)
        else:
            mergedhead = l2
            mergedhead.next = self.mergeTwoLists(l1, l2.next)
        return mergedhead

你可能感兴趣的:(剑指Offer,算法模型,leetcode,链表,递归,双指针,面试)