將兩個已排序之linked list合併。
直接使用合併排序法
程式碼:
# 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, l1: ListNode, l2: ListNode) -> ListNode:
if(not l1 and not l2):
return None
i = 0
while(l1 or l2):
if(i==0):
i+=1
ans = ListNode(0)
target = ans
if(not l1):
ans.next = l2
l2 = l2.next
elif(not l2):
ans.next = l1
l1 = l1.next
else:
if(l2.val>l1.val):
ans.next = l1
l1 = l1.next
else:
ans.next = l2
l2=l2.next
ans = ans.next
return target.next
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up