Skip to content

Instantly share code, notes, and snippets.

@El-Sam
Created October 13, 2017 21:18
Show Gist options
  • Save El-Sam/c8f544d4c06c8ccab0e0555eaa7ab529 to your computer and use it in GitHub Desktop.
Save El-Sam/c8f544d4c06c8ccab0e0555eaa7ab529 to your computer and use it in GitHub Desktop.
Code to merge two sorted linked lists into one sorted linked list by changing the next pointer.
/*
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment