We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
If you move the return statement to inside your conditional blocks, you can clean up your headA > headB code by just allowing it to return headB. Here's my solution in Java:
Node MergeLists(Node a, Node b) {
if (a == null) {
return b;
} else if (b == null) {
return a;
}
if (a.data < b.data) {
a.next = MergeLists(a.next, b);
return a;
} else {
b.next = MergeLists(a, b.next);
return b;
}
}
You can also test for one node == null at a time as I did; if either is null it returns the other, and if both are null returning the second node still returns null which is equivalent to what if((headA==NULL)&&(headB==NULL)) does.
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
If you move the return statement to inside your conditional blocks, you can clean up your headA > headB code by just allowing it to return headB. Here's my solution in Java:
You can also test for one node == null at a time as I did; if either is null it returns the other, and if both are null returning the second node still returns null which is equivalent to what if((headA==NULL)&&(headB==NULL)) does.