使用递归附加链表递归、链表

2023-09-07 10:00:09 作者:范冰冰裸替

我想要一个调用私有递归插入函数的插入函数,该函数将下一个数字添加到链表的末尾.我在应该使用哪些参数以及递归插入函数中应该使用哪些参数时遇到问题.我在想递归插入函数需要一个节点指针来递归地单步执行.

I want an insert function that calls a private recursive insert function that adds the next number to the end of a linked list. I am having trouble on which parameters I should use and what should be in the recursive insert function. I am thinking that the recursive insert function needs a Node pointer to step through recursively.

class LinkedList{
    private:
        struct Node{
            int data; //stores data in nodes
            Node* next;
            ~Node(){delete next;}
        };
    public:
    LinkedList(){ first = NULL;}
    ~LinkedList(){delete first;}

    void print() const {
      print( first );
    }
    void insert(const int d){ //here is where the first insert method is
    insert(first, d);
    }
private:
    Node* first;

这是我卡住的功能...

Here is the function that I am stuck on...

void insert(Node* p, const int d){ //this is the private recursive one
        Node* temp = new Node;
        temp->data=d;
        if(p->next == NULL) p->next = temp;
        else insert(p->next, d);
        }

};

int main() {
int a[] = { 1, 2, 3, 4, 5, 6};
LinkedList list;
  for(int i=0; i<6; i++)
    list.insert( a[i] );
}

我想知道如何通过获取不同的参数来使插入函数重载.我也想知道我是否正确地单步执行了递归函数.

I want to know how to get the insert function to overload by getting the parameters different. I also want to know if I am stepping through the recursive function correctly.

推荐答案

调用递归函数的函数应该是这样的

The function that calls the recursive function should look like

void insert(const int d){
        insert(first, d);
    }

递归函数应该是这样的

void insert(Node*& p, const int d){
    Node* temp = new Node;
    temp->data=d;
    if(p == NULL) p = temp;
    else insert(p->next, d);
}