Last active
April 12, 2017 15:19
-
-
Save anil477/cd7bd61fed1a6cec829f74f59cedbe4e to your computer and use it in GitHub Desktop.
Merge two sorted linked list - iterative
This file contains 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
// 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