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 this class has a special behavior, we will need a function to compare the elements. For this reason, we also need to declare compareFn
({3}
), which will be used to compare the elements. This function will use the defaultCompare...