Skip to content

Instantly share code, notes, and snippets.

@ramytamer
Created January 25, 2016 23:26
Show Gist options
  • Select an option

  • Save ramytamer/20fbf94d0b9e2f87dcc1 to your computer and use it in GitHub Desktop.

Select an option

Save ramytamer/20fbf94d0b9e2f87dcc1 to your computer and use it in GitHub Desktop.
Merge Two Sorted Linked Lists
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