Sorted linked lists

A sorted linked list is a list that keeps its elements sorted. To keep all elements sorted, instead of applying a sorting algorithm, we will insert the element at its correct position so as to keep the list always sorted.

Let's start by declaring the SortedLinkedList class:

const Compare = {  LESS_THAN: -1,  BIGGER_THAN: 1};function defaultCompare(a, b) {  if (a === b) { // {1}    return 0;  }  return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN; // {2}}class SortedLinkedList extends LinkedList {  constructor(equalsFn = defaultEquals, compareFn = defaultCompare) {    super(equalsFn);    this.compareFn = compareFn; // {3}  }}

The SortedLinkedList class will inherit all the properties and methods from the LinkedList class, but since ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.