One Pager Cheat Sheet
- We can create a
Linked List
class to help us append and prepend nodes inO(1)
time and space complexity. - The
linked list
requires ahead
andtail
reference in order to use prepend and append methods. - We will append a new
LinkedListNode
to the list by setting the last node'snext
attribute to the new node, which will always be thenext
of thetail
and the last node in the chain. - We can
prepend
new nodes to a Linked List by creating a new node and setting itsnext
to the current head. Translating
this 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 thehead
andtail
nodes.
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.
xxxxxxxxxx
137
}
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
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.