Most likely you arrived at this article because your preparation for an interview has lead you down a LeetCode rabbit hole. Linked lists are a favorite of many interviewers to test an interviewees understanding of basic data structures as well as your problem solving skills. Whether you’re just a bit rusty from school or this is your first time encountering linked lists they can be a bit tricky to understand at first.
As with most problems it is helpful to start with a diagram. A linked list is a linear data structure which can be thought of as a chain, where each link in a chain is connected to the next link. In a linked list, each link in the chain will be represented as a node.
In a singly linked list, each node contains some data and then a pointer to the next node. For a doubly linked list there would also be a pointer to the previous node. The first node in the list is conventionally referred to as the head and the final node’s next pointer refers to nothing. With this diagram constructed it is now time to start coding up a singly linked list in JavaScript.
Since a singly linked list consists of many notes it makes sense to create a class Node
that way a new node can be easily and consistently instantiated. At the instantiation of a new node the data it will contain should be know but the next node might not be known.
Figure 2: JavaScript Node Class
A doubly linked list node class would look very similar to Figure 2 but with an additional property of previous
that would also initialize to null
as it may not be known or it could be the head node.
#singly-linked-list #javascript #algorithms #data-structures #big-data