用递归附加链表 [英] Append linked list with recursion

查看:30
本文介绍了用递归附加链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于用递归附加链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆