【LeetCode】 1669. Merge In Between Linked Lists
Description
You are given two linked lists: list1
and list2
of sizes n
and m
respectively.
Remove list1
's nodes from the ath
node to the bth
node, and put list2
in their place.
The blue edges and nodes in the following figure indicate the result:
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 →
Build the result list and return its head.
Constraints:
3 <= list1.length <= 10^4
1 <= a <= b < list1.length - 1
1 <= list2.length <= 10^4
給你兩個 linked lists:list1
和 list2
,大小分別為 n
和 m
。
移除 list1
從第 ath
到第 bth
的節點,並將 list2
取代它們的位置。
圖中藍色的邊和節點就是結果。
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 →
建構出答案的 list 並回傳它的開頭。
限制:
3 <= list1.length <= 10^4
1 <= a <= b < list1.length - 1
1 <= list2.length <= 10^4
Example:
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 →
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 →
Solution
- 不需要把多餘的節點移除做記憶體管理,因此只要想辦法建構出答案的 linked list 即可。
- linked list 的更改與陣列不同,不需要每個節點都做修正,只需要針對斷點前後的 node 去修正
next
即可。
- 參考題目第一張圖,我們只需要將
list1
的 a - 1
節點的 next
指向 list2
的開頭,並將 list2
結尾節點的 next
指向 list1
的 b + 1
節點就完成了。
- 因為限制的關係,不需要特別考慮邊緣測資。
Code