Table of Contents
Add nodes recursively at the end
Traverse nodes recursively
Example
The method used in the following program is as follows
Output
Home Backend Development C++ Recursively insert and traverse linked list in C++

Recursively insert and traverse linked list in C++

Sep 10, 2023 am 09:21 AM
recursion Traverse insert

Recursively insert and traverse linked list in C++

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.

Add nodes recursively at the end

  • If head is NULL → add node to head

  • Otherwise add to head( head → next )

Traverse nodes recursively

  • If head is NULL → exit

  • otherwise Print ( head → next )

Example

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

The method used in the following program is as follows

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.

Example

#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;
}
Copy after login

Output

If we run the above code, the following output will be generated

Linked List is :
1 -> 8 -> 56 -> 12 -> 34 -> NULL
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Using the MINUS operator in SQL Using the MINUS operator in SQL Feb 18, 2024 pm 04:53 PM

Usage of MINUS in SQL and specific code examples In SQL, MINUS is an operator used to perform a difference operation between two result sets. It is used to delete the same rows from the first result set as in the second result set. The result set returned by the MINUS operator will contain rows that exist only in the first result set. The following uses specific code examples to demonstrate the usage of MINUS: Assume there are two tables - "table1" and "table2", their structures are as follows: Table name: table1 field

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

Java how to loop through a folder and get all file names Java how to loop through a folder and get all file names Mar 29, 2024 pm 01:24 PM

Java is a popular programming language with powerful file handling capabilities. In Java, traversing a folder and getting all file names is a common operation, which can help us quickly locate and process files in a specific directory. This article will introduce how to implement a method of traversing a folder and getting all file names in Java, and provide specific code examples. 1. Use the recursive method to traverse the folder. We can use the recursive method to traverse the folder. The recursive method is a way of calling itself, which can effectively traverse the folder.

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

Detailed explanation of C++ function recursion: tail recursion optimization Detailed explanation of C++ function recursion: tail recursion optimization May 03, 2024 pm 04:42 PM

Recursive definition and optimization: Recursive: A function calls itself internally to solve difficult problems that can be decomposed into smaller sub-problems. Tail recursion: The function performs all calculations before making a recursive call, which can be optimized into a loop. Tail recursion optimization condition: recursive call is the last operation. The recursive call parameters are the same as the original call parameters. Practical example: Calculate factorial: The auxiliary function factorial_helper implements tail recursion optimization, eliminates the call stack, and improves efficiency. Calculate Fibonacci numbers: The tail recursive function fibonacci_helper uses optimization to efficiently calculate Fibonacci numbers.

See all articles