Append linked list with recursion

萝らか妹 提交于 2021-02-08 10:40:45

问题


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.


回答1:


The function that calls the recursive function should look like

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

The recursive function should look like

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



回答2:


You want to reach the end of the list before you allocate the new node. This version below is most compatible with what you wrote so far.

void insert(Node*& p, const int d) {
    if (p == NULL) { // reached the end, so allocate new node and set value
        p = new Node;
        p->data = d;
        p->next = NULL;
    }
    else
        insert(p->next, d);
}


来源:https://stackoverflow.com/questions/15847251/append-linked-list-with-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!