LinkedList is the dynamic data structure, as we can add or remove elements at ease, and it can even grow as needed. Just like arrays, linked lists store elements sequentially, but donβt store the elements contiguously like an array.
We define a class Node having two properties: element and next. Element holds the data of a node while next holds the pointer to the next node, which is initialized to the null value.
Let's visualize the memory updates step-by-step:
Initial State:
head -> @A1
@A1: { value: 10, next: null }
tail -> @A1
After First Append:
head -> @A1
@A1: { value: 10, next: @B1 }
tail -> @B1
@B1: { value: 5, next: null }
After Second Append:
head -> @A1
@A1: { value: 10, next: @B1 }
@B1: { value: 5, next: @C1 }
tail -> @C1
@C1: { value: 16, next: null }
The entire list structure due to the updates to the next properties.
{
value: 10,
next: {
value: 5,
next: {
value: 16,
next: null
}
}
}
Conclusion
-
tail.next
=newNode
updates thenext
property of the currenttail
node to reference the new node. - This creates a chain of references starting from
head
and extending through each appended node. - Each
append
operation extends the linked list, making the new node part of the chain thathead
points to.
Therefore, while head
itself doesn't change, the structure it references gets updated with each new node appended, because head.next
(and subsequent next
properties) form a chain that includes all nodes, old and new.
Top comments (0)