Certainly! Below is a C++ implementation of a recursive function to merge two singly linked lists u and v by alternating their nodes. If one of the lists becomes empty before the other, the remainder of the non-empty list is appended to the merged list.
Node Definition
First, let's define the structure for a singly linked list node:
struct ListNode {
int val;
ListNode* next;
// Constructor for ease of node creation
ListNode(int x) : val(x), next(nullptr) {}
};
Recursive Merge Function
The mergeAlternately function takes two pointers to the heads of the linked lists u and v and returns the head of the merged list.
ListNode* mergeAlternately(ListNode* u, ListNode* v) {
// Base cases: if one of the lists is empty, return the other
if (u == nullptr) return v;
if (v == nullptr) return u;
// Store the next pointers
ListNode* next_u = u->next;
ListNode* next_v = v->next;
// Link u to v
u->next = v;
// Recursively merge the remaining parts and link v to the result
v->next = mergeAlternately(next_u, next_v);
// Return the head of the merged list
return u;
}
Explanation
-
Base Cases:
- If
u is nullptr, the merged list is simply v.
- If
v is nullptr, the merged list is simply u.
-
Recursive Step:
- Store the next nodes of
u and v to next_u and next_v respectively.
- Link the current node of
u to the current node of v.
- Recursively call
mergeAlternately with the next nodes of u and v and link the result to v->next.
-
Return:
- The head of the merged list is the current node of
u.
Example Usage
Here's how you might use the mergeAlternately function:
#include <iostream>
// Assuming ListNode and mergeAlternately are defined as above
// Helper function to print the list
void printList(ListNode* head) {
while (head != nullptr) {
std::cout << head->val;
if (head->next != nullptr) std::cout << " -> ";
head = head->next;
}
std::cout << " -> nullptr\n";
}
int main() {
// Creating first list: 1 -> 3 -> 5
ListNode* u = new ListNode(1);
u->next = new ListNode(3);
u->next->next = new ListNode(5);
// Creating second list: 2 -> 4 -> 6 -> 8
ListNode* v = new ListNode(2);
v->next = new ListNode(4);
v->next->next = new ListNode(6);
v->next->next->next = new ListNode(8);
// Merging lists
ListNode* mergedHead = mergeAlternately(u, v);
// Printing merged list
printList(mergedHead);
// Clean up memory (not shown for brevity)
return 0;
}
Output:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 8 -> nullptr
This example demonstrates merging two lists where the second list is longer than the first. The merged list alternates nodes from each list and appends the remaining nodes from the longer list once the shorter list is exhausted.