logo CodeStepByStep logo

merge

Language/Type: C++ linked lists pointers
Author: Julie Zelenski (on 2019/05/15)

Write a recursive function named merge that accepts as parameters two pointers to nodes representing the fronts of two linked lists, and returns a pointer to a merged, sorted list containing the combined contents of both lists. For example, suppose your function is given the following lists:

{1, 4, 5, 10, 11}
{2, 4, 6, 7, 8}

A call to your function should return a pointer to the front of the following list:

{1, 2, 4, 4, 5, 6, 7, 8, 10, 11}

Constraints: Do not modify the data field of existing nodes; change the list by changing pointers only. Do not create new ListNode objects, though you may create pointers to nodes. Do not use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc). Do not use any loops; you must use recursion.

Assume that you are using the ListNode structure as defined below:

struct ListNode {
    int data;         // value stored in each node
    ListNode* next;   // pointer to next node in list (nullptr if none)
};
Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.