print linked list recursively c++
To print a linked list recursively in C++, you can follow these steps:
- Define the structure for a node in the linked list. Each node should contain a data field and a pointer to the next node.
struct Node {
int data;
Node* next;
};
- Create a function to print the linked list recursively. This function should take a pointer to the head of the list as a parameter.
void printLinkedList(Node* head) {
// Base case: if the head is null, we have reached the end of the list
if (head == nullptr) {
return;
}
// Print the data of the current node
cout << head->data << " ";
// Recursive call to print the remaining list
printLinkedList(head->next);
}
- In the main function, create the linked list and call the
printLinkedList
function with the head of the list.
int main() {
// Create the linked list
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = nullptr;
// Call the printLinkedList function
printLinkedList(head);
return 0;
}
This code will output: 1 2 3
, which is the data of each node in the linked list, printed recursively.