0 题目描述
leetcode原题链接:剑指 Offer 25. 合并两个排序的链表
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