Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example 1:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Related Topics: Linked List
因為題目給的是兩個有序的鏈結串列,所以這題只須兩個指針分別指向給定的陣列,將節點值較小的添加到新的鏈結串列,添加完後將指標移往下一個節點,直到兩鏈結串列的節點都被添加到新的鏈結串列為止。
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(-1)
head = dummy
while l1 and l2:
if l1.val < l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
head.next = l1 if l1 else l2
return dummy.next
|
Image Not Showing
Possible Reasons
|
呃…其實我對這兩種擴展方式沒啥問題,我是對英文的介係詞有點問題,所以還特地畫了張圖幫助我記憶。因為都要畫圖了,就還是順便整理成一篇網誌,不過應該還是以資工的為主,還是別太糾結我的英文吧 XDDD
Feb 20, 2025categories & tags:
Feb 20, 2025整理一些我自己用過的 LaTex 數學符號指令,下次就不用再像無投蒼蠅般亂找了 XD
Feb 20, 2025之前在整理 [〈GTC 2022 某場演講〉](https://hackmd.io/@CynthiaChuang/Lecture-Notes-Nvidia-GTC-2022#S42424-Deep-Learning-Demystified-for-the-BioPharma-Ecosystem)與[〈CodeFree|喝一杯咖啡,輕鬆學電腦科學〉](https://hackmd.io/@CynthiaChuang/Hiskio-Codefree-Computer-Science-2/#CH-16-1|人工智慧的巨量資料學習法)時,就有打算要整理。不過我拖延症又發作了,導致這篇遲遲難產 ╮(╯▽╰)╭ 。 直到最近文組的朋友問了我這個問題,我才想到躺在草稿夾的這篇,想說好久沒更新網誌了,乾脆把這篇拿出來寫一寫唄!...雖然距離拿出來重寫到現在發出來又過了好長一段時間(掩面
Feb 20, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up