# Leetcode 21. Merge Two Sorted Lists 將兩個已排序之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 ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up