0

Создаю односвязный список с добавлением элемента рекурсивно. Разобралась с функциями ввода/вывода рекурсивно и создала функцию добавления элемента. Подскажите, как последнюю сделать рекурсивно? Буду благодарна!

#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);
        }

1 ответ 1

0

Заменить цикл рекурсией?

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
}
1
  • да, спасибо большое! 20 окт 2019 в 12:18

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.