将for循环转换为递归(C ++)

时间:2020-11-08 17:15:11

标签: c++ recursion

所以我想将此循环(printL,clearL)转换为递归。 我需要进行名为printList,clearList的递归。 而且我不允许使用循环。 请帮助我是C ++的新手,甚至不知道如何开始。 这是完整的代码。

    #include <iostream>
using namespace std;

struct Node { string value; Node* next; };
struct BasketL { Node* items; }; 

void printL(const BasketL& b); 
void clearL(BasketL& b); 
int main() {
    BasketL b3 = { nullptr };
    b3.items = new Node{ "Apple", b3.items };
    b3.items = new Node{ "Banana", b3.items };
    b3.items = new Node{ "Burger", b3.items };
    b3.items = new Node{ "Beef", b3.items };
    b3.items = new Node{ "Pork", b3.items };
    b3.items = new Node{ "Carrot", b3.items };
    b3.items = new Node{ "Cumin", b3.items };
    b3.items = new Node{ "Ice cream", b3.items };
    printL(b3);
    clearL(b3); 
    printL(b3);
    return 0;
}

void printList(const Node* l) {
    //I need to enter converted code here
}

void printL(const BasketL& b) {
    cout <<"BasketL:";
    printList(b.items); // The original for loop part
    /*
    for (Node* l = b.items; l; l = l->next)
        cout <<" " <<l->value;
    */
    cout <<endl;
}

void clearList(Node* l) {
    // I need to enter converted code here
}

void clearL(BasketL& b) {
    printList(b.items); // The original for loop part
    /*
    Node* tmp_next;
    for (Node* l = b.items; l; l = tmp_next) {
        tmp_next = l->next;
        delete l;
    }
    */
    b.items = nullptr; 
}

代码在这里结束 请帮忙

1 个答案:

答案 0 :(得分:2)

足够简单地递归打印列表。

  1. 如果列表为空

  2. 否则,a)打印列表中的第一项,b)打印列表的其余部分

2b是递归部分,您的printList函数调用自身以打印其余列表。这就是使用递归进行循环的方式。

将其放入代码中,您将得到类似的东西

void printList(const Node* l) {
    if (l == nullptr) {
        // list is empty do nothing
    }
    else {
        // print the first item on the list
        cout << ' ' << l->value;
        // print the rest of the list
        printList(l->next);
    }
}

clearList非常相似。如果列表为空,则无需执行任何操作,否则删除列表中的第一项,然后清除列表的其余部分。我把那个留给你。