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)
};