WITHOUT STORING ELEMENTS IN AUXILIAR STRUCTURE
The idea is simple:
-we create a "prev" node -we save a pointer to first prev called "prevHead"
from here we iterate doing the following:
Once the iteration finishes one of the two lists has been fully gone through.
FINISHED!! 😄
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//edge cases
if(l1 == null && l2 == null) return l1;
ListNode prev = new ListNode(-1);//start as a prehead
ListNode prevHead = prev;
while(l1 != null & l2 != null){//While there are nodes in both lists
if(l1.val <= l2.val){
prev.next = l1;
l1 = l1.next;
}else{
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
// at least one of the lists will be left with node/s.
//we just append whats left of l1 or l2 to prev.
if(l1 == null){//append list 2
prev.next = l2;
}else{//append list 1
prev.next = l1;
}
return prevHead.next;
}