• + 5 comments

    My almost similar code in Java. Did not use Recursion because it will give overflow issue with bigger lists.

    Node MergeLists(Node headA, Node headB) {
        Node merged= new Node();
        Node mergedTemp= merged;
        // taking a copy of the head node of new array.
        while(headA !=null || headB !=null)
            {
            // while any of the list has nodes left
            if(headA !=null && headB !=null)
                {
                //while both have elemnts
                if(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 element
                    merged.next=headB;
                    headB=headB.next;
                }
            }
            else if(headA ==null)
                {
                // if list 1 is out of nodes we only add list 2's elements
                merged.next=headB;
                headB=headB.next;
            }
            else if(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;
        }
        return mergedTemp.next;// I started storing elemnts from next location actually thus passing merged.next as head.
    }