Javascript data structures and algorithms
Chapter 1: aN Introduction to javascript chapter 2: An Overview of ECMAscript and TypeScript Chapter 3: Arrays Chapter 4: Stacks Chapter 5: Queues and Double-enantied Columns Chapter 6: Linked Lists
The first chapter js foundation is relatively simple, here I do not waste time to repeat, directly from the second chapter
Chapter 2: Overview of ECMAscript and TypeScript
I focus on data structures and algorithms, so this part is just a general introduction. I have attached a link to the article for details
2.1 Relationship between ECMAscript and JavaScript
The javascript language evolves every year, with a new version released almost every year since 2015. We call it ECMAScript
ECMAScript is a scripting language standardized by Ecma International (formerly the European Computer Manufacturers Association) through ECMA-262. This language is widely used on the World Wide Web and is often referred to as JavaScript or JScript, so it can be understood as a standard for JavaScript, but the latter two are actually implementations and extensions of the ECMA-262 standard.
The relationship between ECMAScript and javascript: the former is a specification of the latter, and the latter is an implementation of the former (also called JScript and Actionsrcipt).
Es5 and ES6 refer to ECMAScript 5 and ECMAScript 6 because
2.2 ECMAScript2015+ (ES6) Functions
ECMAScript5.1 was released in 2011. The first version of ES6 was released in June 2015, so ECMAScript2015+ can be considered as ES6
Es6 provides the following functions
String function using let and const function template parameter default arrow function => class module We will introduce these functions below
2.2.1 Functions and features of let and const
Prior to ES6, there was no block-level scope; As long as the scope of this variable can be accessed; Declare a variable, the JS engine will improve the declaration of the variable.
A variable declared by let is only valid in the block-level scope. It is not valid outside the block-level scope and is destroyed after the function is executed. (var is a global variable.) Const can only be declared as a constant and cannot be changed.
Let and const have several characteristics:
Let and const are local variables and are valid only in their respective scope. There is no variable promotion: declared variables can be used only after they are declared. Declaration variables form a closed scope from the beginning. If you use the variable before declaring it, an error will be reported
2.2.2 Template Strings
The template string is wrapped with a pair of ** ‘ ‘**. To insert the value of the variable, the value needs to put the variable inside the ${}
const name = 'young'
const age = 21
// Traditional string concatenation
console.info('Hello, my name is.' + name + 'This year' + age + 'old')
// Template string usage
console.info('Hello everyone, my name is${name}This year,${age}At the age of `)
Copy the code
2.2.3 Default values of function parameters
Javascript has a built-in object called the Arguments object, which is an array containing the arguments passed to a function when it is called. You can dynamically fetch and use the arguments even if you don’t know their names
ES6 function extensions (function parameter defaults)
2.2.4 Arrow Function =>
ES6 arrow function syntax defines a function, delete the “function” keyword and function name from the original function, and use “=>” to connect the argument list to the function body. Usually the function is written as follows:
var fn1 = function(a, b) {
return a + b
}
function fn2(a, b) {
return a + b
}
Arrow function written as:
var fn1 = (a, b) = > {
return a + b
}
(a, b) => {
return a + b
}
Copy the code
2.2.6 class
In traditional javascript, there is no concept of a class, but in ES6 there is a full understanding of the class class in ES6
2.2.7 module
ES6 uses: import and export instead of require and module.exports to import and export modules
2.3 introduce TypcScript
TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript, and essentially adds optional static typing and class-based object-oriented programming to the language.
TypeScript offers the latest and evolving JavaScript features, including those from ECMAScript 2015 and future proposals, such as asynchronous functionality and Decorators, to help build robust components. The following diagram shows TypeScript in relation to ES5, ES2015, and ES2016:
Chapter 3: Arrays
Mainly learn some methods of array (add, delete, change and check)
3.1 Why Arrays
Arrays are the simplest in-memory data structures that store a series of values of the same data type (javascript arrays can hold different types of values, but try to avoid this). Arrays are designed to simplify recording multiple data and multi-dimensional arrays
3.2 Creating and initializing arrays
There are two ways to create arrays:
Let shuzu=new Array(); Note: Arguments in parentheses can have arguments. If they are a number, they indicate the length of the array. If they are multiple numbers, or one (or more) non-numbers, they indicate the value that should be included in the pass array.
Let shuzu=[];
3.3 Adding Elements
Insert element at the end of array:
Use push method numbers. Push (11);
Native method: numbers[numbers. Length] = 10; In Javascript, arrays are mutable objects that grow dynamically if you want to add elements, so simply assign to the last empty space in the array
2. Insert element at the beginning of array:
Numbers. Unshift (10);
The native method is to create a new array, iterate over the original array, assign the original array to the next bit, copy it to the new array, assign the inserted number to the first position in the new array, and return the new array,
3.4 Deleting an Array
Delete element from end of array:
Use pop method; numbers.pop();
Select * from array;
Use the shif method number.shif();
3. Add or remove elements anywhere
Splice (4.,0,6,4). The first parameter identifies the index value of the element to be deleted or inserted. The second parameter is the number of elements to be deleted. The third argument, after that, is the value we want to add to the array
3.5 Two-dimensional and multidimensional arrays
A two-dimensional array is essentially an array of arrays as array elements, that is, “arrays of arrays”, the type specifier array name [constant expression][constant expression]. A two-dimensional array is also called a matrix, and a matrix with the same number of rows and columns is called a square matrix. Symmetric matrix A [I][j] = a[j][I], diagonal matrix: n-order square matrix with zero elements outside the main diagonal
var arr = [[1.2], ['a'.'b']].console.log(arr[1] [0]); // the element in row 1 of column 2 of a
Copy the code
Similarly, a multidimensional array is basically adding quadrants to a two-dimensional array
3.6 javascript array reference methods
Concat () joins two or more arrays and returns a new array. ES6: copyWithin() copies elements from the specified location in the array to the specified location in the array. CopyWithin (target, start, end) 3, ES6: Entries (), returns an iteration of the array 4. Every (), checks that all the elements in the array match the specified criteria, accepts a function as an argument to check the elements in the array 5. ES6: fill() replaces the elements in the array with a fixed value. Grammar: Array.fill (value, start, end) 6, filter(), return an array containing the qualified elements 7, find(), return the first element in the array 8, findIndex(), ForEach () returns the position of the first element in the array that meets the condition. ES6: from() returns the position of the first element in the array. Includes (), returns true if there is, false otherwise. 12, indexOf(), returns the location of the specified element in the array, -1 if there is no specified element. Return true if yes, false if no 16, lastIndexOf(), returns the last occurrence of the specified element in the array, begins a search at the end of the array 17, map(), returns a new array, Pop () removes the last element of the array and returns the deleted element. 19. Push () adds a new element after the array and returns the new length of the array. ReduceRight () from left to right, calculate the value of the element as a value, from right to left 22, Reverse (), reverse the order of the array elements 23, Shift (), remove and return the first element of the array 24, unshift(), add a new element to the front of the array, Splice (), which adds and deletes elements from the array. The first argument is the start position of the element to be deleted. The second parameter is the number of elements to delete. The third and subsequent arguments are all new elements added to the array. 27, some() checks whether the array contains the specified element and returns true if it does, false if it does not. ValueOf () returns the original valueOf the array object.
3.8 Type Array
Because javascript differs from languages like C and Java, javascript arrays are not strongly typed. You can store any type of data so how do you make javascript arrays store a single type of data? So this is the type array. Specific syntax:
let myArray = new TypedArray(length)
// In real use, replace TypedArray with the type required in the list below
Copy the code
3.9 Arrays in typescript
The simplest approach in Typescript is to use type + square brackets to represent arrays
let fibonacci: number[] = [1.1.2.3.5];
Copy the code
No other types are allowed in array items: When using array methods, the types of the elements added, deleted, or queried must be the same; otherwise, an error will be reported.
TypeScript Array Array operations
Chapter four: Stack
In this chapter, we will learn how to create a stack using arrays and objects in javascript
4.1 Overview of stack
A stack is an ordered collection that follows the first in, last out (LIFO) principle. New elements added or to be removed are stored at the end of the stack, called the top, and the other end is called the bottom. In the stack, the new elements are near the top of the stack, and the old elements are near the bottom of the stack
Using examples from everyday life:
Stacks are like our clothes pockets. What we put in first comes out later, and what we put in later comes out first
Stacks are used in programming language compilers and in memory to hold variables, method calls, etc., and are also used for browser history (the browser’s back button)
4.2 Create a stack based on javascript arrays
Creating a stack with arrays in javascript involves 7 steps:
Add elements to the stack using push (only from the top of the stack). Remove elements from the stack using pop (remove elements from the top of the stack). Check if the stack isEmpty (method peek) 5. Check if the stack isEmpty (method isEmpty) return true if the stack isEmpty and false otherwise 6. 7. You can start using the stack class after the above six steps, stack has nearly the characteristics of the stack.
Code implementation:
// Create an array-based unit stack
class stack{
constructor{
this.items = []; }}// Add elements to the stack using the push method
push () {
this.items.push();
}
// Use the pop method to remove elements from the top of the stack
pop(){
reyurn this.items.pop();
}
// After the above two steps, the basic implementation of the stack principle of first in last out
// Check the top element (length-1)
peek{
return this.items{this.items.length - 1};
}
// use isEmpty to check if the stack isEmptyIsEmpty () {return this.items.length === 0;
}
// After completing the above steps, use the clear method to clear all elements in the stackClear () {return this.items.length;
}
/ / at this point. The stack is completeYou can use the stack method to operate on the stackCopy the code
4.3 Create a stack based on javascript objects
We have learned how to use arrays to create stacks, but in practical applications, when dealing with large amounts of data, we need to evaluate how to use the data most efficiently. The time complexity of using arrays is 0 (n), where n represents the length of the array. Because arrays are ordered collections, to ensure that the elements are sorted, It takes up more memory and we have to iterate through the array until we find the target element.
This leads to the object creation stack where objects can fetch elements directly, take up less memory, and arrange the data according to our requirements.
There are six steps:
1, declare a stack class 2, insert elements into the stack 3, verify that the stack is empty and its size 4, pop elements from the stack 5, check the stack value and empty 6, create a toString method
Code implementation:
// First declare a stack class
class stack {
constructor () {
this.count = 0 ; // Using count to keep track of stack size also helps us remove and add elements
this.items = {}; }}// Add elements to the stackPush (element) {this.items[this.count ] = element;
this.count ++ ;
}
// In js, objects are represented as key-value pairs, we use count as the key name of the items object, and the inserted element is its value. After inserting the element, we add count++ for the next variable value to be inserted
// The count attribute also represents the stack size. We can return the size of count to calculate the stack sizeThe size () {return this.count;
}
// Verify that the stack is empty
isEmpty(){
return this.count === 0;
}
// View the value at the top of the stack and clear the stack
peek{
if (this.isEmpty()){
return unerfined;
}
return this.items{this.items.length - 1};
}
// Empty the stack and change the value to the initial value of the constructorClear () {this.items = {};
this.count = 0;
}
// Another method can be used:
while(!thisIsEmpty ()) {this.pop();
}
// Create the toString methodTostring () {toString () {toString () {toString ();if (this.isEmpty()){
return ' ';
}
let objStru=ing = '${this.items[0]}';
for (let i = 1 ; i < this.count; i++ ){
objString = '${objstring},${this.items[i]}';
}
return objstring ;
}
// If the stack is empty, it is ok to return a null value
// If it is not empty. The first element at the bottom is the initial value of the string, and then the stack is iterated over
Copy the code
At this point, an object-based stack is complete
4.4 Protecting data Structure elements
After we create a stack, other colleagues may also want to use it. We want to protect the elements inside the data structure. Only the elements we expose are allowed to change.
1. Underline naming convention
Some developers like to use the underscore naming convention in javascript to mark a property as a private property. The underscore naming convention actually adds an underscore between property names — but it’s just a convention that doesn’t protect data
Code implementation:
class stack {
constructor () {
this._count = 0;
this._items = {}; }}Copy the code
2, symbol implementation class
The implementation class using Symbol specifies in ES6 that symbol is immutable and can be used as an attribute of an object
Code implementation:
cosnt_items = symbol('stacItems');
class stack {
constoructor () {
this[_items] = [];
}
// stack method
}
Copy the code
3. Use weakMap to implement classes
Using weakMap to achieve class weakMap can ensure that the property is private, weakMap is the existence of key value pairs, keys are objects, values are attributes. This will be highlighted in Chapter 8
4.5 use javascript stack to solve practical problems
Use the stack to achieve recursion of factorial
Use stacks to simulate 5! First push the numbers 5 to 1 on the stack, and then use a loop to pop the numbers one by one and multiply the code:
1 function fact(num) {
2 var stack=new Stack;
3 while(num>0) {4 stack.push(num--);
5 }
6 var sum=1;
7 while(stack.length>0) {8 sum*=stack.pop;
9 }
10 return sum;
11 }
12
13 console.log(fact(5)) / / 120
Copy the code
Legal brackets
The following string contains parentheses. Write a function to check whether the parentheses in the string are valid
SDF (ds) of (ew) (we re RWQW) QWRWQ legal (sd (qwqe), sd (sd)) legal sd () () () (sd) (dw) is illegalCopy the code
If you use an array to store these parentheses, and then try to find a way to cancel one to one, it seems feasible. But we can’t tell which open parenthesis corresponds to which close parenthesis. It’s a little harder to think about this in terms of arrays. Now, we’re going to use a stack to solve this problem and when we see an open bracket, we’re going to push the closing bracket onto the stack and when we see a close bracket, we’re going to see if the stack is empty, and if it’s empty then there’s no open bracket that corresponds to it, so string parentheses are not valid. If the stack is not empty, the top element is removed and the parentheses cancel out. When the for loop ends, if the stack is empty, all the left and right parentheses cancel out, and if there are elements on the stack, the left and right parentheses are missing, and the string parentheses are invalid.
Code implementation:
function is_leagl_brackets(string){
var stack = new Stack();
for (var i = 0; i<string.length; i++) {var item = string[i];
// do parentheses to the stack
if(item == '('){
stack.push(item)
}else if (item == ') ') {// See if the stack is empty
if(stack.isEmpty()){
return false
}else {
stack.pop() // Pop open parenthesis}}}// If the stack is empty, string parentheses are valid
return stack.isEmpty()
}
console.log(is_leagl_brackets('sdf(ds(ew(we)re)rwqw)qwrwq')) // true
console.log(is_leagl_brackets('(sd(qwqe)sd(sd))')) // true
console.log(is_leagl_brackets('()()sd()(sd()dw))(')) // false
Copy the code
Implement a stack with min methods
For a min method, return the smallest element on the stack with time O(1).
function MinStack() {
var data_stack = new Stack();
var min_stack = new Stack();
// Use min_stack to record the minimum value in the stack after each element pushed in
this.push = function (item) {
data_stack.push(item);
if(min_stack.isEmpty() || item < min_stack.top()){
min_stack.push(item)
}else {
min_stack.push(min_stack.top())
}
};
// After each pop, min_stack pops the minimum value from the previous stack
this.pop() = function () {
data_stack.pop()
min_stack.pop()
}
this.min = function () {
return min_stack.top()
}
}
Copy the code
There are many more practical applications, but I won’t list them all here.
Chapter 5: Queues and double-endian columns
5.1 Queue Data Structure
1. The concept of a queue: A queue is an ordered set of columns that follow the first-in, first-out principle. Queues add elements at the tail and remove elements at the top. In daily life, queue for payment, buy food, add people to queue behind, people in front of the payment go first. Queue creation:
Constructor () {this.count = 0; this.lowestCount = 0; // Trace the first element of the queue this.items = {}; }
Enqueue (element) {this.items[this.count] = element; this.count++; }
Size () {return this.count – this.lowestcount; }; isEmpty() { return this.size() === 0; };
Peek () {if (this.isempty ()) {return undefined; } return this.items[this.lowestCount]; }
5. Use isEmpty to check whether the queue isEmpty and get its length 6. Clear () {this.items = {}; this.count = 0; this.lowestCount = 0; }
Tostring () {if (this.isempty ()) {return ‘ ‘; } let objstring = ${this.items[this.lowestCount]}; for (let i = this.lowestCount + 1; i < this.count; i++) { objstring = ${objString},${this.items[i]}; } return objString; }
The method of creating a queue is similar to the stack mentioned above, so I won’t repeat it here
5.2 Dual-Ended Queue Data Structure (DEQUE)
1. Concept of a double-endian queue: A double-endian queue is a special queue that allows us to add and remove elements from both the front and back end of the queue
Deque common application in computer is to store a series of undo operation, the user after the cancellation, the operation will be stored in a deque, can click the undo and vexed withdrawn, because the deque and to abide by the principle of first in first out and last in first out, say that he is to put the queue and stack in combination with a data structure.
2. Create a queue with two ends:
Constructor () {this.count = 0; this.lowestCount = 0; this.items = {}; }
AddFront (element) {if (this.isempty ()) {this.addback (element); } else if (this.lowestCount > 0) {// if (this.lowestCount > 0); this.items[this.lowestCount] = element; } else { for (let i = this.count; i > 0; I -) {this.items[I] = this.items[i-1]; } this.count++; this.items[0] = element; }}
AddBack (element) {this.items[this.count] = element; this.count++; }
RemoveFront () {if (this.isempty ()) {return undefined; } const result = this.items[this.lowestCount]; delete this.items[this.lowestCount]; this.lowestCount++; return result; }
RemoveBack () {if (this.isempty ()) {return undefined; } this. Count -; const result = this.items[this.count]; delete this.items[this.count]; return result; }
PeekFront () {if (this.isempty ()) {return undefined; } return this.items[this.lowestCount]; }
PeekBack () {if (this.isempty ()) {return undefined; } return this.items[this.count – 1]; }
5.3 Applications in Queues and Two-end Teams
Simulate the game of beating drums and passing flowers
Situation: The children circle the city and pass the flowers to the people around them. At a certain point, they stop and the flowers are in the hands of the people around them. Repeat the procedure, and the last person left is the winner. Code implementation:
function hotPotato(elementsList, num) { const queue = new Queue(); const elimitatedList = [];
for (let i = 0; i < elementsList.length; i++) { queue.enqueue(elementsList[i]); }
while (queue.size() > 1) { for (let i = 0; i < num; i++) { queue.enqueue(queue.dequeue()); } elimitatedList.push(queue.dequeue()); }
return { eliminated: elimitatedList, winner: queue.dequeue() }; }Copy the code
Palindrome checker
Check if a phrase waving a string is palindrome. Code implementation:
function palindromeChecker(aString) { if ( aString === undefined || aString === null|| (aString ! = =null && aString.length === 0)) {return false; } const deque = new Deque(); const lowerString = aString.toLocaleLowerCase().split(' ').join(' '); let firstChar; let lastChar;
for (let i = 0; i < lowerString.length; i++) { deque.addBack(lowerString.charAt(i)); }
while (deque.size() > 1) { firstChar = deque.removeFront(); lastChar = deque.removeBack(); if(firstChar ! == lastChar) {return false; }}return true; };Copy the code
Chapter 6: Linked lists
6.1 LinkedList Overview
A linked list stores an ordered collection of elements, but unlike an array, the elements in a linked list are not placed consecutively in memory. Each element consists of a node that stores the element itself and a reference (also known as a pointer or link) to the next element. The illustration below:
One advantage of linked lists over traditional arrays is that you don’t need to move other elements when you add or remove them. However, linked lists require Pointers, so they need to be implemented with care. Another detail of arrays is that you can access any location element directly, whereas to access an element in the middle of the list, you need to start from the starting point (the header) through the list until you find the element you want.
A practical example is the train, which has several carriages that connect to each other, and are connected by connections. The carriage is the element of the linked list, and the connection is the pointer.
6.2 Creating a Linked List
function LinkedList() {
var Node = function (val) {// New element construction
this.val = val;
this.next = null;
};
var length = 0;
var head = null;
this.append = function (val) {
var node = newNode(val);// Construct a new element node
var current;
if (head === null) {// If the head node is null, the current node is the head node
head = node;
} else{ current = head;while(current.next) {// Loop through until next is null and the current node is the last nodecurrent = current.next; } current.next = node;// Point the tail node to the new element, which acts as the tail node} length++;// Update the list length
};
this.removeAt = function (position) {
if (position > -1 && position < length) {
var current = head;
var index = 0;
var previous;
if (position == 0) {
head = current.next;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
length--;
return current.val;
} else {
return null; }};this.insert = function (position, val) {
if (position > -1&& position <= length) {// Check the boundary
var node = newNode(val); current = head;var index = 0;
var previous;
if (position == 0) {// As the head node, next of the new node points to the original head node.node.next = current; head = node;// The new node is assigned to the head node
} else {
while(index++ < position) { previous = current; current = current.next; }// Get the current node where the current position is located and the previous nodeprevious.next = node;// Next of the previous node points to the new node and the new node points to the current node
node.next = current;
}
length++;
return true;
} else {
return false; }};this.toString = function () {
var string = head.val;
var current = head.next;
while (current) {
string += ', ' + current.val;
current = current.next;
}
return string;
};
this.indexOf = function (val) {
var current = head;
var index = -1;
while (current) {
if (val === current.val) { // Start traversal from the beginning node
return index;
}
index++;
current = current.next;
}
return -1;
};
this.getLength = function () {
return length;
}
this.getHead = function () {
returnhead; }}// Create a linked list
var li = new LinkedList();
li.append(1);
li.append(2);
li.append(4);
li.append(4);
li.append(5);
li.insert(2.3);
li.insert(2.3);
console.log(li.toString()) / / 1,2,3,3,4,4,5
console.log(li.getHead()) / / 1 - > 2 - > 3 - > 3 - > 4 - > 4 - > 5
Copy the code
How to create a linked list in JS
6.3 Bidirectional linked lists
The difference between a two-way list and a regular list is that in a one-way list a node has only a link to the next node, whereas in a two-way list a link is a two-way link to the next element and the other link to the previous element.
Bidirectionally linked lists: can be traversed from beginning to end or from end to end. In other words, the process of linked list joining is bidirectional, which is realized by the principle that a node has both a forward connected reference and a backward connected reference. Disadvantages of bidirectional lists: Having to handle four references instead of two each time a node is inserted or deleted can be difficult to implement; Compared with unidirectional linked list, it takes up more memory space; However, these disadvantages are minor compared to the convenience of a two-way linked list.
As shown in the figure:
Code implementation:
// Create a DoubleLinklist class and add basic attributes to it.
// Encapsulate the bidirectional linked list class
function DoubleLinklist(){
// Encapsulate the inner class: node class
function Node(data){
this.data = data
this.prev = null
this.next = null
}
/ / property
this.head = null
this.tail ==null
this.length = 0
}
Copy the code
6.4 Circular linked lists
Each node of a bidirectional linked list needs to join the previous node and the next node, so we need to define two pointer fields, one pointing to the previous node and the next node.
In a bidirectional list, the prev pointer to the head node points to the tail node, and the next pointer to the tail node points to the head node.
Implementation of the loop list:
Create a bidirectional circular linked list
function DoublyCircularLinkedList(){
function Node(element){
this.element=element
this.next=null
this.prev=null
}
let length=0
let head=null
let tail=null
}
Copy the code
2. Insert a new node at the tail
this.append=function(element){
let node = new Node(element)
let current // The current node
let previous // The previous node
if(! head){ head=node tail=node head.prev=tail tail.next=head }else{
current=head
while(current.next ! == head){ previous = current current = current.next } current.next=node node.next=head node.prev=current } length++return true
}
Copy the code
3. Insert nodes at any positions
// Insert a node at any position
this.insert=function(position,element){
if(position > 0 && position <= length){
let node = new Node(element)
let index = 0
let current = head
let previous
if(position === 0) {// Insert the header
if(! head){ node.next=node node.prev=node head=node tail=node }else{
current.prev=node
node.next=current
}
}else if(position === length){ // Insert into the tail
current=tail
current.next=node
node.prev=current
tail=node
node.next=head
}else{
while(index++ < position){
previous=current
current=current.next
}
current.prev=node
node.next=current
previous.next=node
node.prev=previous
}
length++
return true
}else{
return false}}Copy the code
4. Delete nodes based on their locations
this.removeAt = function(position){
if(position > -1 && position < length){
let current = head
let index = 0
let previous;
if(position === 0){
current.next.previous = tail
head = current.next;
}else if(position === length - 1){
current = tail;
current.prev.next = head
head.prev = current.prev
tail = current.prev
}else{
while(index++ < position){
previous = current
current = current.next
}
previous.next = current.next
current.next.prev = previous
}
length--
return true
}else{
return false}}Copy the code
5. Delete the node based on the node value
this.remove = function(element){
let current = head
let previous
let indexCheck = 0
while(current && indexCheck < length){
if(current.element === element){
if(indexCheck === 0){
current.next.prev = tail;
head = current.next
}else{
current.next.prev = previous
previous.next = current.next
}
length--
return true
}
previous = current
current = current.next
indexCheck++
}
return false
}
Copy the code
6.5 Ordered linked lists
An ordered list is a list structure that keeps the elements in order. In addition to using sorting algorithms, we can also insert the elements into the correct positions to ensure the order of the list. Code implementation:
const Compare = {
LESS_THAN: -1.BIGGER_THAN:1
};
function defaultCompare(a,b){
if(a === b){
return 0;
}
returna < b? Compare.LESS_THAN : Compare.BIGGER_THAN; }class SortedLinkedList extends LinkedList{/ / LinkedList class - this class can see https://www.cnblogs.com/MySweetheart/p/13212220.html
constructor(equalsFn = defaultEquals, compareFn = defaultCompare){
super(equalsFn);
this.compareFn = compareFn;
}
insert(element,index = 0){
if(this.isEmpty()){
return super.insert(element,0);
}
const pos = this.getIndexNextSortedElement(element);
return super.insert(element,pos);
}
getIndexNextSortedElement(element){
let current = this.head;
let i = 0;
for(; i <this.size() && current; i++){
const comp = this.compareFn(element,current.element);
if(comp == Compare.LESS_THAN){
return i;
}
current = current.next;
}
returni; }}Copy the code
6.6 Implement stacks with linked lists
JAVASCRIPT – Stack functionality via linked lists
First write the sixth chapter, after I review in writing, there are a lot of places in the book I did not fully understand, so in writing this article introduced a lot of related blog, blog looks easier to understand the code word is not easy, click a praise in go!! I wish you a happy May Day!!
Understanding javascript Data Structures and Algorithms (Middle)
Learn javascript Data Structures and Algorithms: an easy-to-understand primer on TypeScript
JavaScript implements bidirectional linked lists
Review of JavaScript data structures (Part 5-4) bidirectional circular linked lists
Use javaScript to implement an ordered linked list