Linked List Implementation in JavaScript

Level 5533 keystrokes

Implements a singly linked list: each Node holds a value and a link to the next node. append adds 1, 2 and 3 at the end, and toArray walks the list and prints [ 1, 2, 3 ].

JavaScript code

// A Node represents one element of the list
1class Node {
2 constructor(value) {
// Stores the element's value
3 this.value = value;
// Link to the next node; null means this is the last one
4 this.next = null;
5 }
6}
7
// LinkedList keeps a reference to the first node, the head
8class LinkedList {
// A new list is empty, so head is null
9 constructor() { this.head = null; }
// Adds a value at the end of the list
10 append(value) {
// Wraps the value in a new node
11 const node = new Node(value);
// If the list is empty, the new node becomes the head
12 if (!this.head) { this.head = node; return; }
// Otherwise, starts at the head to find the last node
13 let curr = this.head;
// Follows next links until a node has no next
14 while (curr.next) curr = curr.next;
// Links the new node after the last one
15 curr.next = node;
16 }
// Collects the values from head to tail into an array
17 toArray() {
18 const arr = [];
19 let curr = this.head;
// Pushes each value and moves on until curr becomes null
20 while (curr) { arr.push(curr.value); curr = curr.next; }
21 return arr;
22 }
23}
24
// Creates an empty list
25const list = new LinkedList();
// Appends 1, 2 and 3, giving 1 -> 2 -> 3
26list.append(1); list.append(2); list.append(3);
// Prints [ 1, 2, 3 ]
27console.log(list.toArray());

Output

[ 1, 2, 3 ]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ;× 19
  • .× 18
  • (× 15
  • )× 15
  • =× 12
  • {× 8
  • }× 8
  • !× 1
  • [× 1
  • ]× 1

More JavaScript examples at level 5

← JavaScript typing practice