題目:
將兩個升序鏈表合並為一個新的 升序 鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例 1:
輸入:l1 = [1,2,4], l2 = [1,3,4]
輸出:[1,1,2,3,4,4]
示例 2:
輸入:l1 = [], l2 = []
輸出:[]
示例 3:
輸入:l1 = [], l2 = [0]
輸出:[0]
code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1 :
return list2
elif not list2:
return list1
res = ListNode()
ans = res
while list1 != None and list2 != None:
if list1.val <= list2.val:
ans.next = list1
list1 = list1.next
else:
ans.next = list2
list2 = list2.next
ans = ans.next
if list1 == None:
ans.next = list2
else:
ans.next = list1
return res.next