We get the integer value used to form the linked list. The task is to first insert and then traverse the singly linked list using recursive method.
If head is NULL → add node to head
Otherwise add to head( head → next )
If head is NULL → exit
otherwise Print ( head → next )
Input− 1 - 2 - 7 - 9 - 10
Output
Output strong>− Linked list: 1 → 2 → 7 → 9 → 10 → NULL
Input− 12 - 21 - 17 - 94 - 18
Output− Linked list: 12 → 21 → 17 → 94 → 18 → NULL
In this method we will use functions to add nodes and traverse the singly linked list and call them recursively for the next input.
Take a structure SLLNode with an integer and a next pointer SLLNode*.
Function addtoEnd(SLLNode* head, int data) Gets the pointer to the head of the linked list and the integer of the data part, and adds the node to the end of the linked list.
li>If the head pointer is NULL, the list is empty, now add a new node and set it as the head. Add head → next as NULL. Returns a pointer to the node
If head is not null, use head->next = addtoEnd(head->next, data) to add the node to head → next.
Function traverseList(SLLNode* head) Traverses from head and prints each value.
If head is NULL, print NULL and return.
Otherwise, print the data value and use traverseList(head->next) to traverse one.
Use addtoEnd() in the main creation list and use traverseList() to print the list.
#include <bits/stdc++.h> using namespace std; struct SLLNode { int data; SLLNode* next; }; SLLNode* addtoEnd(SLLNode* head, int data){ if (head == NULL){ SLLNode *nodex = new SLLNode; nodex->data = data; nodex->next = NULL; return nodex; } else{ head->next = addtoEnd(head->next, data); } return head; } void traverseList(SLLNode* head){ if (head == NULL){ cout <<"NULL"; return; } cout << head->data << " -> "; traverseList(head->next); } int main(){ SLLNode* head1 = NULL; head1 = addtoEnd(head1, 1); head1 = addtoEnd(head1, 8); head1 = addtoEnd(head1, 56); head1 = addtoEnd(head1, 12); head1 = addtoEnd(head1, 34); cout<<"Linked List is :"<<endl; traverseList(head1); return 0; }
If we run the above code, the following output will be generated
Linked List is : 1 -> 8 -> 56 -> 12 -> 34 -> NULL
The above is the detailed content of Recursively insert and traverse linked list in C++. For more information, please follow other related articles on the PHP Chinese website!