题目:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None
解答:
leetcode优秀方案(来自力扣答案统计页,没有明确作者是谁,可留言告知):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(None) cur = dummy 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 or l2 if not l1: cur.next = l2 if not l2: cur.next = l1 return dummy.next
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 and l2: if l1.val > l2.val: l1, l2 = l2, l1 l1.next = self.mergeTwoLists(l1.next, l2) return l1 or l2 # 作者:QQqun902025048 # 链接:https://leetcode-cn.com/problems/two-sum/solution/python-4xing-by-knifezhu-3/