21. 合并兩個有序鏈表
難度簡單1687收藏分享切換為英文接收動態反饋
將兩個升序鏈表合并為一個新的 升序 鏈表并返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例 1:
img
輸入:l1 = [1,2,4], l2 = [1,3,4]
輸出:[1,1,2,3,4,4]
示例 2:
輸入:l1 = [], l2 = []
輸出:[]
示例 3:
輸入:l1 = [], l2 = [0]
輸出:[0]
提示:
- 兩個鏈表的節點數目范圍是
[0, 50]
-100 <= Node.val <= 100
-
l1
和l2
均按 非遞減順序 排列
- Merge Two Sorted Lists
Easy
6624765Add to ListShare
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:
img
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
- Both
l1
andl2
are sorted in non-decreasing order.
使用遞歸實現,新鏈表也不需要構造新節點
- 終止條件:兩條鏈表分別名為
l1
和l2
,當l1
為空或l2
為空時結束 - 返回值:每一層調用都返回小的鏈表頭,然后返回節點的next節點繼續參與遞歸
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) {//終止條件
return l2;
}
if(l2 == null) {//終止條件
return l1;
}
if(l1.val < l2.val) {//鏈表頭比較大小,誰小誰作為返回節點
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
image-20210429091424544