描述
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:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
複製程式碼
思路
使用迴圈遍歷的方式,將兩個連結串列合併成為一個連結串列。每次合併之前都進行一次比較操作。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//使用-1作為頭部節點,返回連結串列為頭部節點的下一個節點
ListNode out = new ListNode(-1);
ListNode cur = out;
while(l1 != null && l2 != null){
//比較並建立節點,加入連結串列
ListNode new_node;
if(l1.val < l2.val){
new_node = new ListNode(l1.val);
l1 = l1.next;
}else{
new_node = new ListNode(l2.val);
l2 = l2.next;
}
cur.next = new_node;
cur = cur.next;
}
//將剩下的節點拼接在連結串列後面
if(l1 != null){
cur.next = l1;
}else{
cur.next = l2;
}
return out.next;
}
}複製程式碼
Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 39.3 MB, less than 17.51% of Java online submissions for Merge Two Sorted Lists.
另一種思路
使用遞迴的方法,將兩個連結串列進行合併操作。
但是遞迴會導致程式效率變低。
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;
}
}
}複製程式碼
Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 39.3 MB, less than 17.51% of Java online submissions for Merge Two Sorted Lists.