首页 > 解决方案 > 链表指针问题

问题描述

有 2 个 createList 函数,一个打印出链表的所有元素,而另一个没有,为什么会这样?

/*following createList prints out fine */
node* createList(node* root , int a){
    if(root == NULL) root = new node(a);
    else root->next = createList(root->next , a);

    return root;
}

/*following createList prints out only 1st element, why?*/
node* createList(node* root , int a){
    if(root == NULL) root = new node(a);
    else createList(root->next , a);

    return root;
}

void read(node* root){
    if(root==NULL) return;
    else{
        cout << root->data << " ";
        read(root->next);
    }
}

标签: c++recursionlinked-listc++14singly-linked-list

解决方案


在这个函数中

/*following createList prints out only 1st element, why?*/
node* createList(node* root , int a){
    if(root == NULL) root = new node(a);
    else createList(root->next , a);

    return root;
}

它的参数根是函数的局部变量,它保存传递给函数的参数值的副本。因此更改副本不会影响原始参数。

在这个函数中与上面的函数相反

/*following createList prints out fine */
node* createList(node* root , int a){
    if(root == NULL) root = new node(a);
    else root->next = createList(root->next , a);
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    return root;
}

原始参数与新值的分配。

为了更清楚,考虑一个非常简单的程序

#include <iostream>

int f( int x )
{
    x *= 10;

    return x;
}

int main() 
{
    int x = 10;

    std::cout << "Before call of f: " << x << '\n';

    f( x );

    std::cout << "After  call of f: " << x << '\n';

    x = f( x );

    std::cout << "After  call of f: " << x << '\n';

    return 0;
}

它的输出是

Before call of f: 10
After  call of f: 10
After  call of f: 100

在第一次调用该函数后,main 中f的变量x没有改变,因为该函数处理其参数的副本。

在第二次调用函数后,变量发生了x变化,因为它被新值重新分配了。


推荐阅读