how head.next is changed in singly linkedlist ?
Short answer: Because initially both first
and last
are pointing to the same node, last.next = x
indirectly causes first.next = x
.
Long answer:
The heart of it is object reference (pointer).
To understand why it changed, first you have to understand how pointer works in Java, a very high level language where you are hidden from all the nasty yet tedious memory manipulations.
tldr; I would refer you to watch this epic video that talks about pointer, Binky Pointer Video.
How Pointer works in Java
1. Memory allocation:
Statement below allocates new memories to hold node values(data & next). x
is now holding the address value, i.e: 0x1ACD
to actual node value. In other word, x
is a node pointer.
node x = new node(data,null);
2. Pointer Dereferencing:
In order to access the actual node values, we need to dereference the address value. Pointer dereferencing happens when you access properties in Object, i.e: node.Next
. The following statement dereference last
and the object assignment copies the address value in x
to next
(property in last
).
last.next = x
3. Object assignments:
Due to internal Java design (memory efficiency), instead of cloning the entire node value(in real world, it could be huge), object assignments copy only address value.
first
and last
now holds the same address value as x
, which is address to actual node values.
public void add(int data){
...
first = x;
last = x;
...
}
You may ask what is so great about this? Well, take the following example:
public void add(int data){
...
first = x;
last = x;
last.next = new node(123,null);
...
}
Note that now, last.next == first.next
. Changing of node value via last
also appears to modify first
, because both of them are pointing to the same node values.
This is the complete answer to how head.next is changed in singly linkedlist ?
References:
- https://softwareengineering.stackexchange.com/questions/207196/do-pointers-really-exist-in-java
- https://softwareengineering.stackexchange.com/questions/141834/how-is-a-java-reference-different-from-a-c-pointer
Illustrations:
Step 1: When we add(1)
to an empty list:
public void add(int data) {
...
first= x;
...
last = x;
...
}
[1] <- first, last
|
[/] <- first.next, last.next
Step 2: Now, when we add(2)
to the previous list(non-empty):
[1] <- first, last
|
[/] <- first.next, last.next
public void add(int data) {
...
last.next= x;
...
last = x;
...
}
[1] <- first
|
[2] <- last
|
[/] <- last.next
Step 3 and etc: Now, let's add(3)
or subsequent values to the list(non-empty):
[1] <- first
|
[2] <- last
|
[/] <- last.next
public void add(int data) {
...
last.next= x;
...
last = x;
...
}
[1] <- first
|
[2]
|
[3] <- last
|
[/] <- last.next
Note:
first
always pointing to first node in list.
last
always pointing to last node in list.
last.next
is always pointing to null. Via Add()
, a new node is always appended to the end of the list via assignment to last.next
.