Madan Lal
Madan Lal

Reputation: 31

Pointers in C++ / Linked List

Lets say in my linked list class I am keeping a pointer that refers to the head of the linked list...

In one of the member functions when I write this code...

Node *cur = head;
cur = cur->next;

why doesn't head change head->next?

if I write cur = NULL; will it make head null?

Upvotes: 2

Views: 511

Answers (3)

Foggzie
Foggzie

Reputation: 9821

If you write:

Node *cur = head;
cur = NULL;

then cur will be pointing to nothing and nothing will happen to head.

If you write:

Node *cur = head;
cur = cur->next;
cur = NULL;

The same thing will happen (cur will be pointing to nothing and nothing will happen to head) unless head was NULL, in which case, you'll crash on cur = cur->next;

If you're trying to set head->next to NULL via the cur pointer, you can do so with the following:

Node *cur = head;
cur->next = NULL;

I can see your confusion is coming from the nature of pointers. When you say Node *cur = head; you are creating a Node pointer that points to the same memory address as head. If you set cur to something else via cur = NULL, then you're only changing what cur points to, not the value of what it's pointing to and therefore, head is left alone.

When you use cur->next = NULL instead, you're modifying the next member of what cur points to. This is also the next member of what head points to and therefore, the change is also reflected in head->next.

Upvotes: 2

lcs
lcs

Reputation: 4245

I'm assuming that head is a Node *. In this case, when you say cur = cur->next you are changing where cur points, but head will remain pointing to the head of the list because you haven't changed where it points.

Cur----------|
             |
             V       next
Head -----> Item 1--------->Item 2

cur = cur->next yields the following:

Cur--------------------------|
                             |
                     next    V      
Head -----> Item 1--------->Item 2

Upvotes: 7

user1252446
user1252446

Reputation:

cur is pointer, cur = cur->next; merely make cur point somewhere else, why should it change head?

Upvotes: 1

Related Questions