Skip to content

Instantly share code, notes, and snippets.

@lcanady
Last active August 19, 2021 23:55
Show Gist options
  • Select an option

  • Save lcanady/fc705b8f9093d4e6a20f11dac12f7746 to your computer and use it in GitHub Desktop.

Select an option

Save lcanady/fc705b8f9093d4e6a20f11dac12f7746 to your computer and use it in GitHub Desktop.
class ListNode {
/**
* Create a new node
* @param {*} value The value to assign to the linked list.
* @param {ListNode | null} next The pointer to the next node in the chain
*/
constructor(value, next = null) {
// The value of the node. Can be anything.
this.value = value;
// the pointer to the next node in the chain.
this.next = next;
}
}
class LinkedList {
/**
* Create a new Linked List
*/
constructor() {
// Size of the linked list
this.size = 0;
// a pointer to the first node
this.head = null;
// a pointer to the last node.
this.tail = null;
}
/**
* Add a value to teh beginning of the linked list.
* @param {*} value The value to assign to the linked list.
* @returns {LinkedList}
*/
prepend(value) {
// create a new node in memory
// Make it's 'next' point to the memory address currently in this.head.
// currently at this.head.
const node = new ListNode(value, this.head);
// set this.head to the address of the new node.
this.head = node;
// If there is no tail (if this is the first entry)
// set this.tail to point to the memory address for node.
if (!this.tail) this.tail = node;
// inc sizr
this.size++;
// return 'this' so we can chain multiple
return this;
}
/**
* Add a value to the end of the linked list.
* @param {*} value The value to add
* @returns {LinkedList}
*/
append(value) {
// Create a mew mpde in memory
const node = new ListNode(value);
// If there are no nodes, make a the pinters to our new node,
if (this.size === 0) {
this.head = node;
this.tail = node;
} else {
// else if there already nodes in the list
// set the next value in the node currently in this.tail.
this.tail.next = node;
// Set the tail pointer to the address of the new node.
this.tail = node;
}
// Increase the list size
this.size++;
return this;
}
/**
* Print details about the linked list
*/
print() {
console.log("HEAD:", this.head);
console.log("TAIL:", this.tail);
console.log("SIZE:", this.size);
console.log(JSON.stringify(this, null, 2));
}
}
// instantiate the new class
const list = new LinkedList();
// write some tests!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment