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.

一刷
題解:合并兩個排序的單鏈表, 創建一個dummy head,然后進行合并。 Time Complexity - O(n),Space Complexity - O(1)。

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(-1);
        ListNode header = res;
        while(l1!=null && l2!=null){
            if(l1.val <= l2.val){
                res.next = l1;
                res = res.next;
                l1 = l1.next;
            }
            else{
                res.next = l2;
                res = res.next;
                l2 = l2.next;
            }
        }
        
        while(l1!=null){
            res.next = l1;
            res = res.next;
            l1 = l1.next;
        }
        
        while(l2!=null){
            res.next = l2;
            res = res.next;
            l2 = l2.next;
        }
        
        return header.next;
    }
}

二刷:
思路很簡單,每次取l1, l2中較小的值作為下一個node, 注意dummy node的使用

/**
 * 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 dummy = new ListNode(-1);
        ListNode cur = dummy;
        while(l1!=null && l2!=null){
            if(l1.val < l2.val){
                cur.next = new ListNode(l1.val); 
                l1 = l1.next;
            }
            else{
                cur.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            cur = cur.next;
        }
        
        while(l1!=null){
            cur.next = l1;
            l1 = l1.next;
            cur = cur.next;
        }
        
        while(l2!=null){
            cur.next = l2;
            l2 = l2.next;
            cur = cur.next;
        }
        
        return dummy.next;
        
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容