Singly linked list recursively

Creating a singly linked list with the addition of an element recursively. I figured out the input/output functions recursively and created a function for adding an element. Can you tell me how to do the latter recursively? I will be grateful!

#include <iostream>

using namespace std;

struct tnode {
    int info;
    tnode *next;

};
typedef tnode *pnode;


pnode Formback_Ree() //rec done
{
    pnode top;
    int info;
    cin>>info;
    if (!info) return NULL;
    top= new tnode;
    top-> info=info;
    top-> next =Formback_Ree();

    return top;
}
int insert_after(pnode top, int info, int newinfo) { //вставка элемента
    pnode cur, newNode;

    if (top == NULL) //проверка на пустоту
        return 0;
    cur = top;
    while (cur) {
        if (cur->info == info) { //cовп ли мой эл с нужным
            newNode = new tnode; //выделяем
            newNode->info = newinfo;
            newNode->next = cur->next;
            cur->next = newNode;
            return 1;
        }
       cur = cur->next;
      //  insert_after((cur->next), info, newinfo);
    }
    return 0;
}
void output1(pnode a) 
{
    pnode cur;
    cur = a;
    if (cur){
    cout << cur->info << " ";
    output1(cur->next);
    }
    return;
}
 int main() {
        pnode d;
        d= Formback_Re();

        int info1;
        int newinfo1;
        cout << "\n(after) Введите номер элемента N:\n";
        cin >> info1;

        cout << "\n(after) Введите номер нового элемента N:\n";
        cin >> newinfo1;
        if (insert_after(d, info1, newinfo1)) {
            cout << "(after) Элемент N: " << newinfo1 << " успешно добавлен.\n";
            output1(d);
        }
Author: Ivanna Vasilkova, 2019-10-20

1 answers

Replace the loop with a recursion?

int insert_after(pnode top, int info, int newinfo) { //вставка элемента
    if(!top) return 0;
    if(top->info == info) {
        top->next = new node{newinfo, top->next};
        return 1;
    }
    return insert_after(top->next, info, newinfo); // recursion step
}
 0
Author: bipll, 2019-10-20 11:04:21