剑指Offer25-合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:
0 <= 链表长度 <= 1000
来源:力扣(LeetCode)
链接:力扣
一解
判定两个节点“val”,将小的一方放到尾结点的“next”中:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 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 not l1:
return l2
if not l2:
return l1
if l2.val > l1.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
tmp = head
while l1 and l2:
if l2.val > l1.val:
tmp.next = l1
l1 = l1.next
else:
tmp.next = l2
l2 = l2.next
tmp = tmp.next
tmp.next = l1 if l1 else l2
return head
二解
思路与“一解”相同,“二解”使用额外结点“ListNode(0)”减少代码量:
# 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:
head = tmp = ListNode(0)
while l1 and l2:
if l2.val > l1.val:
tmp.next, l1 = l1, l1.next
else:
tmp.next, l2 = l2, l2.next
tmp = tmp.next
tmp.next = l1 if l1 else l2
# 注意:结果返回 head.next
return head.next