Merge Two Sorted Lists

題目
思路:

  1. 因為要做一個 linked list,可以用 while 在每次迴圈都接一個 node 出來

  2. 先設 while True:,等寫迴圈內容時再來確定 while 可繼續執行的條件

  3. 寫第一 part (如下) 後發現,while 條件需要 l1 and l2

    1
    2
    3
    4
    5
    6
    if l1.val > l2.val:
    curr.next = l2
    l2 = l2.next
    else:
    curr.next = l1
    l1 = l1.next
  4. post processing: 跳出迴圈後的情形是 l1, l2 其中有一個是 None 或兩個都是 None,此時就把目標 linked list 接上那個不是 None 的即可

Python3 solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode() # 因為不知道第一個會用 l1 還 l2,所以用 dummy_head
curr = dummy_head # 也要有個 curr 可以在每次迴圈中跟著移動
while l1 and l2:
if l1.val > l2.val:
curr.next = l2
l2 = l2.next
else:
curr.next = l1
l1 = l1.next
curr = curr.next
curr.next = l1 or l2 # post processing
return dummy_head.next

P.S. 有些思路跟 Add Two Numbers 重複,這篇就不多寫了

評論

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×