Merge k Sorted Lists


#1

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

#2

Uses divide and conquer like mergesort. Repeatedly divide the list to sort and merge. Below is the golang solution for Merge K Sorted Lists

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeKLists(lists []*ListNode) *ListNode {
    if len(lists) == 0{
        return nil
    }
    return sort(lists, 0, len(lists)-1) 
}

func sort(lists []*ListNode, l, r int) *ListNode {
    if l==r{
        return lists[l]
    }
    
      mid := (l+r)/2
        
      l1 :=  sort(lists, l, mid)
      l2 :=  sort(lists, mid+1, r)
        
    return merge(l1, l2)
}



func merge(l1 *ListNode, l2 *ListNode) *ListNode {
    if l1 == nil {
		return l2
	}
	if l2 == nil {
		return l1
	}
    
    head := &ListNode{Val : 0, Next : nil}
    phead := head
    
    for l1!=nil && l2!=nil{
        if l1.Val < l2.Val {
            head.Next = &ListNode{Val :l1.Val, Next: nil}
            l1 = l1.Next
        } else {
            head.Next = &ListNode{Val :l2.Val, Next: nil}
            l2 = l2.Next
        }
        
        head = head.Next
        
    }
    
    for l1!=nil{
        head.Next = &ListNode{Val :l1.Val, Next: nil}
        head = head.Next
        l1 = l1.Next
    }
    
    for l2!=nil{
       head.Next = &ListNode{Val :l2.Val, Next: nil}
        head = head.Next
       l2 = l2.Next
    }
    
    return phead.Next
}