You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = [] Output: []
Example 3:
Input: list1 = [], list2 = [0] Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50]. -100 <= Node.val <= 100- Both
list1andlist2are sorted in non-decreasing order.
SOL:
原本想練習 148. Sort List,但發現又是merge sort、又是linked list,就算看了講解也聽不太懂,所以先來回來複習一下linked list。
然後因為我python都無腦用list,結果開始分不清array跟list的差異。
array跟list的差異看這篇:用記憶體管理講解為何 python 的 list 那麼慢
這一題也是merge sort的merge部分(拿掉遞迴),所以也回去複習了merge sort。
linked list使用起來,還是有很多細節要注意:
1. 一開始宣告一個空的 ListNode,要有一個head去記住,否則之後在使用的時候會被弄丟。
參考這篇:[LeetCode] 21. Merge Two Sorted Lists
linked list,一定需要保留head這個node,它是一個入口,每次要使用這個linked list,都要從這個入口進行,一個個node下去找值;另一個常用的,就是用current node,來指涉現在要進行處理的node。
然後寫while的條件的時候開始分不清 and, & 的差異,據說 and = && (C++)才是邏輯運算。
比對了別人的程式之後,發現當只剩 list1 跟 list2的時候,可以不用再一個個去while遞迴,直接把整個剩下的放入result就可以了。
可以簡寫成這樣,更帥!
2022.12.26 C語言寫法:
參考:leetcode 21. Merge Two Sorted Lists(C语言,合并两个排序的链表为一个排序链表)32
