1

i am working with linked list,and I have one possibly stupid question.I have class Node for linked list which contains attribute Node as next element,and I have this line:

Node current=head;
while(current!=null)
current=current.next;

I don't understand why head doesn't also change,but only current?And why does it change only if I do current.next=current.next.next,how can that reflect anyhow on head?I understand that with current=current.next we iterate through current(head),and it changes current,but why doesn't it change head also?Thank you in advance!

slomil
  • 193
  • 1
  • 4
  • 12
  • 2
    You're confused between mutating a variable and mutating an object. – Sotirios Delimanolis Aug 31 '17 at 20:37
  • aha,`a` and `b` here are objects,and head is variable..but why then `current.next=current.next.next` change head??when head is not changed with `current=current.next`?do you know maybe? – slomil Aug 31 '17 at 20:46
  • It might help you understand this to draw this on paper. Each `Node` instance is a box, and each variable (`current`, `head`, `next`) is an arrow pointing to some `Node` (or nothing for `null`). – chrylis -cautiouslyoptimistic- Aug 31 '17 at 20:57

0 Answers0