Merge Two Sorted Linked Lists I solved this problem in C++. I was having trouble though understanding what return headA; and return headB; returns after going back down the recursion tree. A code review is also appreciated!


  You’re given the pointer to the head nodes of two sorted linked lists.
  The data in both lists will be sorted in ascending order. Change the
  next pointers to obtain a single, merged linked list which also has
  data in ascending order. Either head pointer given may be null meaning
  that the corresponding list is empty.


/*
  Merge two sorted lists A and B as one linked list
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
#include &lt;iomanip&gt;

Node* MergeLists(Node *headA, Node* headB)
{
    // check if either linked list is empty, then return the other one. when doing recursive, a new headA and headB will be passed in, so it will add the entire list correctly
  if (headA == NULL) {
      return headB;
  } else if (headB == NULL) {
      return headA;
  } else { // if neither empty go into this block
      if (headA-&gt;data &lt;= headB-&gt;data) {
          headA-&gt;next = MergeLists(headA-&gt;next, headB);
          // returns the entire linked list after the recursion parses it in the correct order
          // not too sure what is returned going down the recursion tree
          // headA = 1 -&gt; 3 -&gt; 5 -&gt; 6 -&gt; NULL
          // headB = 2 -&gt; 4 -&gt; 7 -&gt; NULL
          // would it return 6, 5, 3, 1, 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7 after recursion tree?
          return headA;
      } else {
          headB-&gt;next = MergeLists(headA, headB-&gt;next);
          // return 7, 4, 2 after recursion tree?
          return headB;
      }
  }
}
Your solution is fine, subject to the caveat that the use of recursion imposes a limit on the length of your lists, due to the possibility of stack overflow.

Your comments betray a sense of insecurity about how it works, though.  Just consider what happens locally, and trust that recursion will take care of the rest.

I also suggest un-nesting the else block.

/**
 * Recursively merge two sorted lists by manipulating node pointers.
 * Returns the head of the merged list.
 */
Node* MergeLists(Node *headA, Node* headB)
{
    if (headA == NULL) {
        return headB;
    } else if (headB == NULL) {
        return headA;
    } else if (headA-&gt;data &lt;= headB-&gt;data) {
        headA-&gt;next = MergeLists(headA-&gt;next, headB);
        return headA;
    } else {
        headB-&gt;next = MergeLists(headA, headB-&gt;next);
        return headB;
    }
}