DEV Community

manoj
manoj

Posted on

DSA: Linked List Javascript

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.

Image description
Let's visualize the memory updates step-by-step:

Initial State:

head -> @A1
@A1: { value: 10, next: null }
tail -> @A1
Enter fullscreen mode Exit fullscreen mode

After First Append:

head -> @A1
@A1: { value: 10, next: @B1 }
tail -> @B1
@B1: { value: 5, next: null }
Enter fullscreen mode Exit fullscreen mode

After Second Append:

head -> @A1
@A1: { value: 10, next: @B1 }
@B1: { value: 5, next: @C1 }
tail -> @C1
@C1: { value: 16, next: null }
Enter fullscreen mode Exit fullscreen mode

The entire list structure due to the updates to the next properties.

{
  value: 10,
  next: {
    value: 5,
    next: {
      value: 16,
      next: null
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • tail.next = newNode updates the next property of the current tail 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 that head 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.

Demo

Top comments (0)