One Pager Cheat Sheet
- We can create a
Linked Listclass to help us append and prepend nodes inO(1)time and space complexity. - The
linked listrequires aheadandtailreference in order to use prepend and append methods. - We will append a new
LinkedListNodeto the list by setting the last node'snextattribute to the new node, which will always be thenextof thetailand the last node in the chain. - We can
prependnew nodes to a Linked List by creating a new node and setting itsnextto the current head. Translatingthis into code results in a boldly structured sentence.- We can achieve
O(1)time and space complexity for bothappend()andprepend()by saving a reference to both theheadandtailnodes.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx137
}var assert = require('assert');​class MyLinkedList { constructor() { this.head = null; this.tail = null; }​ prepend(newVal) { const currentHead = this.head; const newNode = new LinkedListNode(newVal); newNode.next = currentHead; this.head = newNode;​ if (!this.tail) { this.tail = newNode; } }​ append(newVal) { const newNode = new LinkedListNode(newVal); if (!this.head) { this.head = newNode; this.tail = newNode; } else { this.tail.next = newNode; this.tail = newNode; } }​ toString() { const toPrint = [];OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.

