简体   繁体   中英

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 ?

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM