criskgl
9/25/2019 - 10:29 AM

Merge k sorted lists

Merge K sorted lists

  • What we do here is to put inside a queue the pointers to the nodes that we have to evaluate

We start mergin an empty list (null pointer) and the first element stored in queue

Then we loop :

  • We set the current list to result of last merge
  • We merge current list to next element in queue

We iterate until our queue is empty aaaaand its done 😁

public ListNode mergeKLists(ListNode[] lists) {
    //handle edge cases
    if(lists.length == 0) return null;
    if(lists.length == 1) return lists[0];
    
    Queue<ListNode> listsQ = new LinkedList<>();
    for(ListNode listi : lists){
        listsQ.add(listi);
    }
    ListNode finalList = null;
    while(listsQ.isEmpty() == false){
        ListNode current = listsQ.poll();
        finalList = mergeTwoLists(finalList, current);
    }
    return finalList;
}
  
  //This function merges two lists.
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  //edge cases1
  if(l1 == null) return l2;
  if(l2 == null) return l1;
  ListNode prev = new ListNode(-1);//start as a prehead
  ListNode prevHead = prev;
  while(l1 != null & l2 != null){//While there are nodes in both lists
      if(l1.val <= l2.val){
          prev.next = l1;
          l1 = l1.next;
      }else{
          prev.next = l2;
          l2 = l2.next;
      }
      prev = prev.next;
  }
  // at least one of the lists will be left with node/s.
  //we just append whats left of l1 or l2 to prev.
  if(l1 == null){//append list 2
      prev.next = l2;
  }else{//append list 1
      prev.next = l1;
  }
  return prevHead.next;
}