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.
My almost similar code in Java. Did not use Recursion because it will give overflow issue with bigger lists.
NodeMergeLists(NodeheadA,NodeheadB){Nodemerged=newNode();NodemergedTemp=merged;// taking a copy of the head node of new array.while(headA!=null||headB!=null){// while any of the list has nodes leftif(headA!=null&&headB!=null){//while both have elemntsif(headA.data<=headB.data)// if list 1 has smaller element add its node to the new list.{merged.next=headA;headA=headA.next;}else{// else add list 2's elementmerged.next=headB;headB=headB.next;}}elseif(headA==null){// if list 1 is out of nodes we only add list 2's elementsmerged.next=headB;headB=headB.next;}elseif(headB==null){// else if list 2 is out of elements we add list 1's elements;merged.next=headA;headA=headA.next;}merged=merged.next;}returnmergedTemp.next;// I started storing elemnts from next location actually thus passing merged.next as head.}
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
My almost similar code in Java. Did not use Recursion because it will give overflow issue with bigger lists.