4

why does the runner pointer not changed to null?

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

but in the following, it does change to null

Node* reversedList = head;
reversedList->next = nullptr;
Node* runner = head->next;
cdonts
  • 9,304
  • 4
  • 46
  • 72
ineedhelp
  • 59
  • 1
  • 9

2 Answers2

2

After you issue the following statement

Node* runner = head->next;

'runner' points to address memory pointed by 'next' (let's say it is address 0x6543).

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

The following two lines:

Node* reversedList = head;

reversedList->next = nullptr;

So, 'next' points to NULL now, but 'runner' still points to the address previously pointed by 'next', i.e., 0x6543.

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

The second example works because first you make head->next points to NULL then you make 'runner' points to head->next, that now is NULL. As 'head' and 'reversedList' both points to same address the second example -- without reversedList -- would be:

head->next = nullptr; 

Node* runner = head->next;
eribeiro
  • 572
  • 3
  • 7
  • shouldn't this line from the snippet that doesn't change the runner pointer to nullptr change the value in its address to null: reversedList->next = nullptr; thus runner should have been changed to nullptr? or maybe the question should be, why doesn't it change the value in that address to nullptr? – ineedhelp Aug 23 '15 at 03:09
  • Nope. nullptr is dealing with pointers to memory addresses, not the content of those addresses. http://stackoverflow.com/a/20509811 – eribeiro Aug 23 '15 at 03:14
  • An analogy would be: you take two pieces of paper and write the same telephone number on both. Then you tear one paper (set to nullptr). You still have the other piece of paper intact -- with the telephone number on it --, as well as it doesn't discard the telephone. ;) – eribeiro Aug 23 '15 at 04:54
0

In the first one you store the pointers head and head->next in reversedList and runner respectively. Then you change reversedList->next to be nullptr, but runner was a copy of head-next not a reference to the pointer itself. Therefore it didn't change.

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