Skip to content

Instantly share code, notes, and snippets.

@andyku25
Created April 5, 2021 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyku25/3aefa529b74acc0007ac33e2bf5a5f43 to your computer and use it in GitHub Desktop.
Save andyku25/3aefa529b74acc0007ac33e2bf5a5f43 to your computer and use it in GitHub Desktop.
Example of a doubly linked list data structure with ability to append and prepend nodes and traverse to search for a specific value.
class Node {
constructor(value) {
this.value = value,
this.next = null
this.prev = null
}
}
class LinkedList {
// Set the head and tail to null as there are no nodes currently
constructor(head, tail) {
this.head = null,
this.tail = null
}
// traversing through list starting at the head and check if the value exists in the list
find(value) {
let currentHead = this.head
while (currentHead) {
console.log(currentHead.value)
if (currentHead.value === value) {
return currentHead;
}
currentHead = currentHead.next;
}
return null;
}
// Add a new node to the End of the list
append(value) {
if (!this.tail) {
// sets this new node as the head and tail if the list was empty
this.head = this.tail = new Node(value);
} else {
// temporarily set the last node to a variable oldTail
const oldTail = this.tail;
// Create a new node
const newNode = new Node(value);
// Set the new node to be the new tail
this.tail = newNode
// point the old tail to the new node to ensure they are linked
oldTail.next = newNode;
// Set the previous pointer to point at the oldTail ensuring the link is chained
this.tail.prev = oldTail
}
}
// add a new node to the Start of the list
prepend(value) {
if (!this.head) {
this.head = this.tail = new Node(value);
} else {
const oldHead = this.head;
this.head = new Node(value)
this.head.next = oldHead;
oldHead.prev = this.head;
}
}
}
// Create a new list
const linked1 = new LinkedList
// Add a few nodes to the list
linked1.append(123);
linked1.append(456);
linked1.append(789);
linked1.prepend(0);
// View the structure of the list
console.log(linked1);
console.log("------------------");
// Search the list for a specified value. returns the node if found otherwise returns null
console.log(linked1.find(45));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment