Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active April 12, 2017 15:19
Show Gist options
  • Save anil477/cd7bd61fed1a6cec829f74f59cedbe4e to your computer and use it in GitHub Desktop.
Save anil477/cd7bd61fed1a6cec829f74f59cedbe4e to your computer and use it in GitHub Desktop.
Merge two sorted linked list - iterative
// https://github.com/careermonk/DataStructureAndAlgorithmsMadeEasyInJava/blob/master/src/chapter03linkedlists/MergeSortedListsRecursion.java
public class MergeSortedListsIterative {
public ListNode mergeTwoLists(ListNode head1, ListNode head2) {
ListNode head = new ListNode(0);
ListNode curr = head;
while(head1 != null && head2 != null){
if(head1.data <= head2.data){
curr.next = head1;
head1 = head1.next;
}else{
curr.next = head2;
head2 = head2.next;
}
}
if(head1 != null)
curr.next = head1;
else if(head2 != null)
curr.next = head2;
return head.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment