Try   HackMD

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

其他連結

  1. 【LeetCode】0000. 解題目錄



本文作者:辛西亞.Cynthia
網站連結辛西亞的技能樹 / hackmd 版本
版權聲明:部落格中所有文章,均採用 CC BY-NC-SA 4.0 許可協議。轉載請標明作者、連結與出處!

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →