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 list1class Node {2 constructor(value) { // Stores the element's value3 this.value = value; // Link to the next node; null means this is the last one4 this.next = null;5 }6}7 // LinkedList keeps a reference to the first node, the head8class LinkedList { // A new list is empty, so head is null9 constructor() { this.head = null; } // Adds a value at the end of the list10 append(value) { // Wraps the value in a new node11 const node = new Node(value); // If the list is empty, the new node becomes the head12 if (!this.head) { this.head = node; return; } // Otherwise, starts at the head to find the last node13 let curr = this.head; // Follows next links until a node has no next14 while (curr.next) curr = curr.next; // Links the new node after the last one15 curr.next = node;16 } // Collects the values from head to tail into an array17 toArray() {18 const arr = [];19 let curr = this.head; // Pushes each value and moves on until curr becomes null20 while (curr) { arr.push(curr.value); curr = curr.next; }21 return arr;22 }23}24 // Creates an empty list25const list = new LinkedList();// Appends 1, 2 and 3, giving 1 -> 2 -> 326list.append(1); list.append(2); list.append(3);// Prints [ 1, 2, 3 ]27console.log(list.toArray());Output
[ 1, 2, 3 ]
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