【问题标题】:Append linked list with recursion使用递归附加链表
【发布时间】:2013-03-28 15:43:08
【问题描述】:

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

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;

这是我卡住的功能...

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

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

【问题讨论】:

    标签: recursion insert linked-list append nodes


    【解决方案1】:

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

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

    【讨论】:

    • 看起来每次调用insert(Node,int) 时都会为节点分配内存。追加到长列表时会浪费大量内存吗?如果是,那么最好等到实际使用的时候再创建新节点。
    【解决方案2】:

    您希望在分配新节点之前到达列表末尾。下面这个版本和你目前写的最兼容。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多