![]() |
VOOZH | about |
The task is to implement a singly linked list with two core functionalities using recursion:
Insertion: Insert a new node at the end of the linked list.
Traversal: Traverse the linked list and print the data stored in each node.
Example :
Input: Values to be inserted = 1, 2, 3, 4, 5
Output: 1 -> 2 -> 3 -> 4-> 5 -> NULL
Explanation : We have to first recursively insert each node with the given input value and then print the linked list recursivelyInput: Values to be inserted = 7, 8, 4, 11, 44, 6
Output: 7 -> 8 -> 4 -> 11 -> 44 -> 6 -> NULL
Approach :
Define a Node class/struct with data and a reference to the next node. Implement a recursive function to insert a new node at the end of the list. Finally, use a recursive traversal function to print the data of each node in the list.
Follow the steps below to solve the problem:
1. Insert a Node: Write a function that adds a new node to the end of the list. If the list is empty, this new node becomes the first node. If the list already has nodes, the function will keep moving to the next node until it finds the last one, then adds the new node there.
2. Traverse the List: Write a function to go through each node in the list, starting from the first one. While traversing each node, it will print out the data stored in that node. This function will keep moving to the next node until it reaches the end of the list.
Below is the implementation of the above approach:
1 2 3 4 5
Time Complexity: O(n), to traverse the linked list of size n
Auxiliary Space: O(n), for recursion call stack