A Tidbit About Linked Lists…
As a bootcamp graduate, most data structures were unknown to me. I became familiarized with arrays and objects during my five months in an immersive software engineering course, but other structures — like linked lists — were completely new to me once I began my job search.
So what are linked lists, exactly? Linked lists are a simple data structure that consists of nodes. There are two types of linked lists: singly linked lists, and doubly linked lists. Singly linked lists point forward in one direction, while doubly linked lists can point forward and/or backwards.
The first node of a linked list is called the head. Some folks refer to the tail as the last node in the list, but others refer to it as every node that comes after the head. Each node has a value, and a pointer that leads to the next node (with the exception of the tail, which points to null). They are similar to arrays in the sense that they are a linear data structure, except they are not indexed. This can make inserting data in linked lists faster than arrays, since we’re not required to shift the indexes with each change.
Unfortunately, linked lists are not built in JavaScript, so in order to use one, you must write your own. I’ve implemented my own singly linked list below with methods for inserting a node at the beginning of the list, inserting at the end, and printing the current list.
class Node { constructor(value, next) { this.value = value, this.next = next }}class LinkedList { constructor() { this.head = null, this.size = 0 } insertFirst(value) { this.head = new Node(value, this.head) this.size++ } insertLast(value) { let newNode = new Node(value, null) let current = this.head while (current.next) { current = current.next } current.next = newNode this.size++ } printData() { let current = this.head while (current) { console.log(current.value) current = current.next } }}
Seeing my singly linked list, are you up for the challenge of expanding it into a doubly linked list?