鏈接:https://leetcode.com/problems/merge-two-sorted-lists/#/description
難度:Easy
題目:21. Merge Two Sorted Lists
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.
翻譯:合并兩個排好序的鏈列,并將其作為新鏈表返回。新鏈表應通過將前兩個列表的節點拼接在一起。
思路一:新建一個頭指針指向0的臨時鏈表,比較l1和l2的當前值的大小,把臨時鏈表的next節點指向較小的節點,l1或者l2的指針后移一位,依次往下,直到l1或者l2為空,則把臨時鏈表的next節點指向最后那段非空的鏈表,返回臨時鏈表的第二個節點(頭一個節點為0)。
參考代碼一(Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newList = new ListNode(0);
ListNode nextList = newList;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
nextList.next = l1;
l1 = l1.next;
}else{
nextList.next = l2;
l2 = l2.next;
}
nextList = nextList.next;
}
if(l1 != null){
nextList.next = l1;
}else{
nextList.next = l2;
}
return newList.next;
}
}
思路二:使用遞歸法。構造一個臨時鏈表,當l1當前節點的值大于l2當前節點的值時,我們把l2這個較小的值賦給臨時鏈表的下一個節點,并將l2的下一個節點的值和l1當前節點的值放到下一次做對比,依次遞歸下去。
參考代碼二(Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val > l2.val) {
ListNode tmp = l2;
tmp.next = mergeTwoLists(l1, l2.next);
return tmp;
} else {
ListNode tmp = l1;
tmp.next = mergeTwoLists(l1.next, l2);
return tmp;
}
}
}