將兩個升序鏈表合併爲一個新的升序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
鏈表的表頭head可以設計成一個指向第一個節點的指針,也可以設計成一個val爲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 l1 is None:
return l2
elif l2 is None:
return l1
# head是排序新鏈表的表頭,讓它指向第一個節點
if l1.val < l2.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
cnode = head
while l1 and l2:
if l1.val < l2.val:
cnode.next = l1
l1 = l1.next
else:
cnode.next = l2
l2 = l2.next
cnode = cnode.next
if l2:
cnode.next = l2
else:
cnode.next = l1
return head