devlazar

Posted on

Elementary Data Structures with JavaScript - Linked Lists - PART 2π

* π€ INTRODUCTION
* π’ CREATING A NODE
* πADD ELEMENT TO THE TAIL OF THE LIST
* πCREATE A LINKED LIST FROM AN ARRAY
* βDELETING ELEMENTS FROM A LIST
* βCHECK IF AN ELEMENT WITH SPECIFIC VALUE IS IN THE LIST
* π¨π»βπ»CODE
* π THANK YOU

π€ INTRODUCTION

Welcome, my dear hackers!π Welcome to yet another blog article about elementary data structures.

If you missed the previous article where we describe the Linked Lists and write pseudocode, you can check it out here:

Today we are going to implement the Singly-Linked list using JavaScript programming language.

π’ CREATING A NODE

Every node of the singly linked list, consists of the info or the value stored in the node, and the pointer that points to the next node of the list. Let's create a class describing the node.

Since we are creating a Singly-Linked list, I am going to name the class "SLList". The class has a couple of class member variables and those are length (or size) of the list, a pointer to the head of the list, a pointer to the tail of the list.

We need to implement a function that will add a new element to the head of the list.

π ADD ELEMENT TO THE TAIL OF THE LIST

This function will provide logic for adding a new element at the tail of our linked list.

π CREATE A LINKED LIST FROM AN ARRAY

Let's assume that our user wants to provide an array of elements, but it is required from us to convert that array into the linked list in the respective order. We will do it like this:

1. Check if the provided value is an array
2. If it is, we call a member function that will traverse an array and call our addToHead function. I will omit some code so that we can display a nice image.

β DELETING ELEMENTS FROM A LIST

This is the most complex function that we will implement. This function needs to differentiate if we were to delete the first (head), the last (tail), or any other element with the specified value. But, we will also provide an indicator that will override the function to delete the first element it encounters with the specified value.

β IS IN LIST

This function will check if our list includes an element with a specific value.

π¨π»βπ» CODE

And finally our code!