DEV Community

Cindy Lam
Cindy Lam

Posted on

Linked List - Basics

Linked List Brief Intro:

  • Linear collection data structure
  • Chain of nodes ⛓ - "each node contains a value and a pointer to the next node in the chain."
Singly Linked List (one direction only)

1 -> 2 -> 3 -> 4 -> null (when the pointer gets to null, it has reached the end of the linked list) 
^
Head: beginning of the linked list 
Enter fullscreen mode Exit fullscreen mode
//Linked List Node Class Declaration
class ListNode { 
   constructor(value = 0, next = null) { 
      this.value = value; 
      this.next = next; 
   }
}
Enter fullscreen mode Exit fullscreen mode

In this Linked List series, I will be using curr (stands for current) as the main pointer to move through a Linked List.

//Using curr allows us to remember the head to return it at the end of the function

let curr = head; 
Enter fullscreen mode Exit fullscreen mode
1 -> 2 -> 3 -> 4 -> null
^
curr

curr = ListNode { 
          value: 1, 
           next: ListNode { 
                   value: 2, 
                    next: ListNode { 
                             value: 3, 
                              next: ListNode {
                                     value: 4, 
                                      next: null
                                   }
                          }
                 }
       }
curr.value = 1
Enter fullscreen mode Exit fullscreen mode
1 -> 2 -> 3 -> 4 -> null
^ ->
curr.next (the next node based on the current node) 

curr.next = ListNode{2, ListNode{3, ListNode{4}}}
curr.next.value = 2
Enter fullscreen mode Exit fullscreen mode

How to move to the next node in a Linked List?

//assigning curr to the next node 
curr = curr.next; 
Enter fullscreen mode Exit fullscreen mode

Here is an example:

while(curr) { //keep iterating as long as curr is not null
   curr = curr.next; 
}
Enter fullscreen mode Exit fullscreen mode
While 'curr' is not null: 

1 -> 2 -> 3 -> 4 -> null
^ ->
curr.value = 1
curr.next.value = 2

curr = curr.next;

__

While 'curr' is not null: 

1 -> 2 -> 3 -> 4 -> null
     ^ ->
curr.value = 2
curr.next.value = 3

curr = curr.next;

__

While 'curr' is not null: 

1 -> 2 -> 3 -> 4 -> null
          ^ ->
curr.value = 3
curr.next.value = 4

curr = curr.next;

__

While 'curr' is not null: 

1 -> 2 -> 3 -> 4 -> null
               ^ ->
curr.value = 4
curr.next = null

curr = curr.next; 

__

1 -> 2 -> 3 -> 4 -> null
                     ^ ->
'curr' is null, stop the iteration. 
The pointer has now moved through the entire Linked List. 
Enter fullscreen mode Exit fullscreen mode

References & Additional Resources:

Top comments (0)