Skip to content

Instantly share code, notes, and snippets.

@CalamityAdam
Created May 3, 2019 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CalamityAdam/24836ff93dd9cb23ca31f91e2707627e to your computer and use it in GitHub Desktop.
Save CalamityAdam/24836ff93dd9cb23ca31f91e2707627e to your computer and use it in GitHub Desktop.
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
};
/**
* Given a LinkedList and a value, return true if the value exists in the list, if not return false
*/
const doesValueExist = (list, value) => {
// grab head as variable
let node = list.head;
// as long as a node exists, traverse the list
while (node) {
// if we found the value, return true!
if (node.value === value) {
return true;
// else redefine node as the node.next and continue traversing
} else {
node = node.next;
}
}
// if we got here, we're at the end of the list and have not found our value, return false;
return false;
}
/**
* Given a LinkedList and a value, add the value (as a new node) on the list as the head
*/
const addToHead = (list, value) => {
// create new node to insert
const newHead = new Node(value)
// grab old head as a variable
let oldHead = list.head;
// redefine new head
list.head = newHead;
newHead.next = oldHead;
}
/**
* Given a LinkedList and a value, add the value (as a new node) on the list as the tail
*/
const addToTail = (list, value) => {
// create new node to insert
const newTail = new Node(value)
// grab head as variable
let node = list.head;
// if there is no head, set new node as head and return
if (!node) {
return list.head = newTail;
}
// as long as there is a node.next keep traversing. if there is NO node.next, we are at the tail.
while (node.next) {
node = node.next;
}
// set the tai's next as the new tail
node.next = newTail;
};
/**
* Given a LinkedList, a value, and an index, insert the value (as a new node) in the list at the given index
*/
const insertAtIndex = (list, value, index) => {
// create new node to insert
const newNode = new Node(value);
// start counter to keep track of current index
let counter = 0;
// grab head as variable
let node = list.head;
// traverse until we are at the node BEFORE the index we want to insert
while (counter < index) {
counter++;
if (!node.next) {
// handle edge case of index is greater than available nodes
throw new Error('No node at the given index');
}
node = node.next;
}
// when we are at index BEFORE the index we want to insert, assign new node's next as the node.next's node
newNode.next = node.next;
// reassign node.next as the new node
node.next = newNode;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment