Created
January 25, 2016 23:26
-
-
Save ramytamer/20fbf94d0b9e2f87dcc1 to your computer and use it in GitHub Desktop.
Merge Two Sorted Linked Lists
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
| Node MergeLists(Node headA, Node headB) { | |
| Node list1 = headA; | |
| Node list2 = headB; | |
| Node newList = null; | |
| Node lastNode = null; | |
| int toPut = 0; | |
| while (list1 != null || list2 != null) { | |
| if (list1 == null && list2 == null) | |
| break; | |
| if(list2 == null){ | |
| toPut = list1.data; | |
| list1 = list1.next; | |
| } | |
| else if(list1 == null){ | |
| toPut = list2.data; | |
| list2 = list2.next; | |
| } | |
| else if(list1.data < list2.data){ | |
| toPut = list1.data; | |
| list1 = list1.next; | |
| } | |
| else{ | |
| toPut = list2.data; | |
| list2 = list2.next; | |
| } | |
| Node newNode = new Node(); | |
| newNode.data = toPut; | |
| if (newList == null) | |
| lastNode = newList = newNode; | |
| else | |
| lastNode = lastNode.next = newNode; | |
| } | |
| return newList; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment