Below is the implementation of the AddLast() method
"
var temp = new Node(value);
if (first == null)
{
first = temp;
last = temp;
}
else
{
last.nextNode = temp;
last = temp;
}
"
I was debugging to understand how this works.
list.AddLast(1); If condition will be executed. First will be equal to last
list.AddLast(2); Else condition will be executed. When “last.nextNode = temp;” is executed, it will also update first.nextNode.
list.AddLast(3); Else condition will be executed. When “last.nextNode = temp;” is executed, it will also update first.nextNode.nextNode. How will it happen?
Could anyone please explain why first.nextNode.nextNode is updated when last.nextNode is updated during the “list.AddLast(3)” execution.
I am not able to understand the AddLast method implementation. Mainly the else part.
LinkedList exercise to implement “addLast” method
Below is the implementation of the AddLast() method as in the solution.
public void AddLast(int value)
{
var temp = new Node(value);
if (first == null)
{
first = temp;
last = temp;
}
else
{
last.nextNode = temp;
last = temp;
}
}
Consider we add three elements to linked list using AddLast() method.
When “list.AddLast(1)” is executed - If condition of the AddLast method will be executed. First will be equal to last
When “list.AddLast(2)” is executed - Else condition of the AddLast method will be executed. last.nextNode is updated. It also updates first.nextNode
When “list.AddLast(3)” is executed - Else condition of the AddLast method will be executed. last.nextNode is updated. It also updates first.nextNode.nextNode.
I want to understand why first node values are updated when we update the last node value. Is it because of “pass by reference”
Thank you so much for the explanation.
Sorry if I am asking very basic question.
My doubt is how come first node’s next field gets updated when we update the last node. In the code we are actually updating the last node and not making any change for first node.
It is because the references point to the same objects.
By the time you are adding the 3 to the linked list, there are two existing objects already in the linked list and two pointers (one pointing to each of those objects).
Trying to visualize it looks like this:
1 (first) -> 2 (last) -> null
3 -> null
Those arrows (->) indicate what the “next” pointer is pointing to and I have put the first and last pointers in parentheses.
So when we update last.next to point to our new node, that would look like this:
1 (first) -> 2 (last) -> 3 -> null
Then we update the last pointer to point at the new node:
1 (first) -> 2 -> 3 (last) -> null
So we are not directly changing first.next, it just happens to point the the same object that last pointed to.