If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sure! To display the elements of a singly linked list recursively, we can use a recursive function to traverse the linked list from the head node to the tail node. Here's the C++ implementation:
cppCopy code#include <iostream> using namespace std; // Node structure for singly linked list struct Node { int data; Node* next; }; // Function to create a new node with the given data Node* createNode(int data) { Node* newNode = new Node(); newNode->data = data; newNode->next = nullptr; return newNode; } // Function to insert a new node at the end of the linked list void insertEnd(Node*& head, int data) { Node* newNode = createNode(data); if (head == nullptr) { head = newNode; return; } Node* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newNode; } // Recursive function to display the elements of the linked list void displayLinkedListRecursive(Node* current) { if (current == nullptr) { cout << endl; return; } cout << current->data << " "; displayLinkedListRecursive(current->next); } // Function to free memory allocated for the linked list void deleteLinkedList(Node*& head) { while (head != nullptr) { Node* temp = head; head = head->next; delete temp; } } int main() { Node* head = nullptr; // Inserting elements into the linked list insertEnd(head, 1); insertEnd(head, 2); insertEnd(head, 3); insertEnd(head, 4); insertEnd(head, 5); // Displaying the linked list recursively cout << "Linked List: "; displayLinkedListRecursive(head); // Free memory and delete the linked list deleteLinkedList(head); return 0; }
In this code, the
displayLinkedListRecursive
function is used to display the linked list recursively. The function takes the current node as an argument and prints its data value. Then, it calls itself with the next node until it reaches the end of the list (i.e., when the current node isnullptr
).When you run this code, it will display the elements of the linked list:
1 2 3 4 5
. The recursive display will print the elements in the same order as the iterative display.
Copyright Disclaimer under Section 107 of the copyright act 1976, allowance is made for fair use fo purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational or personal use tips the balance in favor of fair use.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform