Skip to content

Instantly share code, notes, and snippets.

@El-Sam
Created October 13, 2017 21:18
Show Gist options
  • Select an option

  • Save El-Sam/c8f544d4c06c8ccab0e0555eaa7ab529 to your computer and use it in GitHub Desktop.

Select an option

Save El-Sam/c8f544d4c06c8ccab0e0555eaa7ab529 to your computer and use it in GitHub Desktop.

Revisions

  1. El-Sam created this gist Oct 13, 2017.
    47 changes: 47 additions & 0 deletions mergeTwoSortedLinkedLists.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    /*
    Merge two linked lists
    head pointer input could be NULL as well for empty list
    Node is defined as
    class Node {
    int data;
    Node next;
    }
    */

    Node mergeLists(Node headA, Node headB) {
    if(headA == null && headB == null)
    return null;

    if(headA == null)
    return headB;

    if(headB == null)
    return headA;

    Node root = (headA.data < headB.data)? headA: headB;

    while(headA != null && headB != null){

    if(headA.data < headB.data){
    if((headA.next == null) || (headA.next != null && headB.data < headA.next.data)){
    Node tmp = headB.next;
    headB.next = headA.next;
    headA.next = headB;

    headB = tmp;
    }
    headA = headA.next;
    }else {
    if((headB.next == null) || (headB.next != null && headA.data < headB.next.data)){
    Node tmp = headA.next;
    headA.next = headB.next;
    headB.next = headA;

    headA = tmp;
    }
    headB = headB.next;
    }
    }

    return root;
    }