DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

Linked List

Hey, let´s talk about linked Lists and what are the differences between an array and a linked list.

Linked List
A linked list is structured by objects, each object have a head and a next value.

Image description

*A linked List in javascript will look like this
*

const list = {
    head: {
        value: 1
        next: {
            value: 20                                             
            next: {
                value: 22
                next: {
                    value: 21
                    next: null  
                    }
                }
            }
        }
    }
};

Enter fullscreen mode Exit fullscreen mode

Some disadvantage that linked list have are the following.

  • It is slower because random access like in an array is not allowed.

  • It uses more memory because of the storage of the pointer

Creating a javascript class as a ListNode

class ListNode{
  constructor(data){
    this.data = data
    this.next = null
   }
}
Enter fullscreen mode Exit fullscreen mode

Crating a javascript class as a Linked List

class LinkedList{
  constructor(head = null){
   this.head = head
   }
}
Enter fullscreen mode Exit fullscreen mode

*Now we will put all it together
*

We`ll create two list nodes and then a pointer from node 1 to node 2


let node1 = new ListNode(2)
let node2 = new ListNode(5)
node1.next = node2

If we break down the code we will see that on the the first line we are defining node1 equal to a new listNode(2) where 2 is the value we are assigning to node1, then we do the same on the second line.
On the third line however we are defining the value of the node1 pointer where we are telling to it to be equal to node2.

Now we`ll create a linked list with the node1

let list = new LinkedList(node1)
Enter fullscreen mode Exit fullscreen mode

Here we are defining list to be a linked list and we are assigning it the node1 value.

Let`s try to access to it.


console.log(list.head.next.data)

It will return 5, but why?
Let`s see, when we access list.head.next we are telling it to go to the next node and the last data is to access the data when we are in a linkedList.

Thanks for reading it, i hope you found it somehow helpful.

Lautaro.

Top comments (2)

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
lausuarez02 profile image
Lautaro Suarez

Nice, thank you.
I did not know i can put colors on my codeblocks