我的思绪目前很困惑:
struct Node {
int data;
struct Node *next;
}
void Print(Node *head) {
}
Run Code Online (Sandbox Code Playgroud)
这是HackerRank的代码片段.虽然这很容易,但我刚开始想知道:如果我在Print函数中修改了头部,它是否也修改了main中的原始头部,还是只修改了局部变量头?
您按值传入指针,如果您修改该指针,则它不会影响原始指针.
但是,如果您修改该指针所指向的内容,那么它将影响原始指针.
例如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.
Run Code Online (Sandbox Code Playgroud)
由于它使用head->next并最终修改结果,因此它将修改原始列表.