Why doesn't the runner pointer below go to zero?

why didn't the runner pointer change to zero?

Node* runner = head->next; Node* reversedList = head; reversedList->next = nullptr; 

but in the following case it will change to null

 Node* reversedList = head; reversedList->next = nullptr; Node* runner = head->next; 
+4
source share
2 answers

After you follow the instructions below

 Node* runner = head->next; 

'runner' points to the address memory indicated by "next" (for example, this is address 0x6543).

(head-> next) ------> content <---- (runner)

The following two lines:

 Node* reversedList = head; reversedList->next = nullptr; 

So, "next" now points to NULL, but "runner" still points to the address previously indicated by "next", that is, 0x6543.

(head-> next) → NULL | content <-------- (runner)

The second example works because first you make head-> next points equal to NULL, then you make "runner" points to head-> next, now it is NULL. Like the "head" and the "reverseedList", both points to the same address, the second example - without reverseedList - would be:

 head->next = nullptr; Node* runner = head->next; 
+2
source

In the first, you store the head and head->next pointers in reversedList and runner respectively. Then you change reversedList->next to nullptr , but runner is a copy of head-next , not a reference to the pointer itself. Therefore, he has not changed.

But in the second you did reversedList->next nullptr and then made a copy of the next pointer (which you just made nullptr ), so the copy is nullptr

0
source

All Articles