Good afternoon! Here's our prompt for today.
Let's implement a linked list, a data structure
that serves as one of the fundamental building blocks of many other data structures.

A linked list is defined as a linear
data structurewhere each element is a separate object. Each element (we will call it a node) of a list is comprising of two items - the data and a reference to the next node.
Traditionally we have the following LinkedListNode
class definition:
1class LinkedListNode {
2 constructor(val, next = null) {
3 this.val = val;
4 this.next = next;
5 }
6}
We can readily create a entire linked list
by writing statements like:
1const list1 = new LinkedListNode(2);
2list1.next = new LinkedListNode(3);
This will append the node to the end of our new list, and does the job most of the time. However, what if we wanted to make things cleaner and implement a class to help us append and prepend nodes?
Given the following skeleton for a Linked List class, can you fill in the #append
and #prepend
methods? We will call .head
on an instance of your class to get the head node.
1class LinkedList {
2 constructor() {
3 this.head = null;
4 this.tail = null;
5 }
6
7 prepend(value) {}
8
9 append(value) {}
10};
Constraints
- The numbers in the node to be added are within the integer limits
- Expected time complexity for appending and prepending :
O(1)
- Expected space complexity for appending and prepending :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
'PASSED: Prepending 15, appending 5, prepending 7, appending 19 should equal `7 -> 15 -> 5 -> 19`'
var assert = require('assert');
​
class MyLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
​
prepend(value) {
// prepend a value
}
​
append(value) {
// append a value
}
​
toString() {
// helper method
const toPrint = [];
let currNode = this.head;
​
while (currNode) {
toPrint.push(currNode.val);
currNode = currNode.next;
}
​
return toPrint.join(' -> ');
}
}
Here's our guided, illustrated walk-through.
How do I use this guide?