Southee
Southee

Reputation: 69

The status of head in this linked list

My mind is confused at the moment:

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

void Print(Node *head) {

}

This is a code snippet from HackerRank. While this is easy, I just started wondering something: If I modify the head in the Print function, does it modify the original head in the main as well, or is it just the local variable head that is modified?

Upvotes: 0

Views: 42

Answers (1)

Guvante
Guvante

Reputation: 19203

You passed in a pointer by value, if you modify that pointer then it will not affect the original.

However if you modify what is pointed to by that pointer then it will affect the original.

For instance head = nullptr; would not, while head->data = 1; would.

Also note that any recursion you do will similarly change the original data, for instance an algorithm to add to the end of the list:

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

Since it uses head->next and eventually modifies the result it will modify the original list.

Upvotes: 5

Related Questions