題目
思路:
因為要做一個 linked list,可以用 while 在每次迴圈都接一個 node 出來
先設
while True:,等寫迴圈內容時再來確定 while 可繼續執行的條件寫第一 part (如下) 後發現,while 條件需要
l1 and l21
2
3
4
5
6if l1.val > l2.val:
curr.next = l2
l2 = l2.next
else:
curr.next = l1
l1 = l1.nextpost processing: 跳出迴圈後的情形是
l1,l2其中有一個是None或兩個都是None,此時就把目標 linked list 接上那個不是None的即可
Python3 solution:
1 | def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: |
P.S. 有些思路跟 Add Two Numbers 重複,這篇就不多寫了