将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
分析
- 双指针
- 注意保存头节点
- 分类讨论
# 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:
if l1 is None:
return l2
if l2 is None:
return l1
cur1 = l1
cur2 = l2
if cur1.val <= cur2.val:
cur = ListNode(cur1.val)
cur1 = cur1.next
else:
cur = ListNode(cur2.val)
cur2 = cur2.next
result = cur
while cur1 is not None and cur2 is not None:
if cur1.val <= cur2.val:
cur.next = ListNode(cur1.val)
cur1 = cur1.next
else:
cur.next = ListNode(cur2.val)
cur2 = cur2.next
cur = cur.next
if cur1 is not None:
cur.next = cur1
elif cur2 is not None:
cur.next = cur2
return result