此链接列表中的头部状态

时间:2015-02-26 17:42:03

标签: c++

目前我的想法很困惑:

struct Node {
    int data;
    struct Node *next;
}

void Print(Node *head) {

}

这是HackerRank的代码段。虽然这很容易,但我刚开始想知道:如果我在Print函数中修改了头部,它是否也修改了main中的原始头部,还是只修改了局部变量头?

1 个答案:

答案 0 :(得分:5)

按值传入指针,如果修改指针则不会影响原始指针。

但是,如果修改该指针指向的内容,则会影响原始指针。

例如head = nullptr;不会,而head->data = 1;则会。

另请注意,您执行的任何递归都将类似地更改原始数据,例如要添加到列表末尾的算法:

Node* previous = head
Node* current = head->next;
while (current != nullptr)
{
    previous = current;
    current = previous->next;
}
previous->next = new Node(); //However you create one.

由于它使用head->next并最终修改结果,因此会修改原始列表。