I'm learning Data structures and came across this problem - merging two sorted linked list. I have gone through the recursive solution, and it seems pretty straight forward. I wanted to try an iterative solution and came up with this.
private static Node mergeListsIterative(Node headA, Node headB) {
if (headA == null) {
return headB;
}
if (headB == null) {
return headA;
}
Node head;
if (headA.data < headB.data) {
head = headA;
headA = headA.next;
} else {
head = headB;
headB = headB.next;
}
Node temp = head;
while (headA != null && headB != null) {
if (headA.data < headB.data) {
temp.next = headA;
headA = headA.next;
} else {
temp.next = headB;
headB = headB.next;
}
temp = temp.next;
}
if (headA == null) {
temp.next = headB;
} else {
temp.next = headA;
}
return head;
}
I saw this post on SO which uses an iterative approach. I feel that my code is simpler. Please review my code and tell me if it can be simplified.