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.

难度:easy

Solution: Merge Sort

对于建立一个新的list,删除一个元素和插入一个元素等问题,一般都需要一个dummy head。

/**
 * 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 dummyHead = new ListNode(0);
        ListNode ptr = dummyHead;
        while(l1 != null || l2 != null) {
            if(l1 != null && (l2 == null || l1.val <= l2.val)) {
                ptr.next = l1;
                ptr = l1;
                l1 = l1.next;
            }
            if(l2 != null && (l1 == null || l2.val <= l1.val)) {
                ptr.next = l2;
                ptr = l2;
                l2 = l2.next;
            }
        }
        return dummyHead.next;
    }
}

Merge K Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

难度:hard 还有一种解法是利用最小堆。

Solution: Merge Sort

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        return mergeKListsHelper(lists, 0, lists.length - 1);
    }
    private ListNode mergeKListsHelper(ListNode[] lists, int start, int end) {
        if(start > end) {
            return null;
        }
        if(start == end) {
            return lists[start];
        }
        if(start == end - 1) {
            return mergeTwoLists(lists[start], lists[end]);
        }
        int mid = start + ((end - start) >> 1);
        return mergeTwoLists(mergeKListsHelper(lists, start, mid), mergeKListsHelper(lists, mid + 1, end));
    }
    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode ptr = dummyHead;
        while(l1 != null || l2 != null) {
            if(l1 != null && (l2 == null || l1.val <= l2.val)) {
                ptr.next = l1;
                ptr = l1;
                l1 = l1.next;
            }
            if(l2 != null && (l1 == null || l2.val <= l1.val)) {
                ptr.next = l2;
                ptr = l2;
                l2 = l2.next;
            }
        }
        return dummyHead.next;
    }
}

results matching ""

    No results matching ""