Created
October 13, 2017 21:18
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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