Home Web Front-end JS Tutorial Detailed explanation of the list of Javascript data structures and algorithms_javascript skills

Detailed explanation of the list of Javascript data structures and algorithms_javascript skills

May 16, 2016 pm 04:10 PM
javascript list data structure algorithm

Foreword: In daily life, people often use lists. For example, when we sometimes go shopping, in order to buy all the things when shopping, we can make a list of the things we want to buy before going. This is the list we use. Or when we were in school when we were young, after each exam, the school would list the rankings and transcripts of the top ten students who scored in the exam, and so on. These are all examples of the list. We also use lists in our computers, so where are lists suitable for use? Where is it not suitable for use?

Suitable for use: When there are not many elements in the list, you can use the list, because the efficiency is very high when searching or sorting the elements in the list. On the contrary: If there are very many elements in the list, then Lists are no longer suitable.

1: Abstract data type definition of list

In order to design the abstract data type of the list, we need to give the definition of the list, including what attributes the list should have, what operations should be performed on the list, etc.

A list is an ordered set of data. The data items in each list are called elements. In JavaScript, elements in a list can be of any data type. There is no prior agreement on how many elements can be stored in a list. However, the number of elements is limited by the program memory in actual use.

Now we want to design a list, then we can think about implementing a list and what attributes and methods they should contain. Of course, my following designs are based on the demo in the "Javascript Data Structure and Algorithm" book. So far we can learn how to design our own abstract class as a reference when we write programs in the future. The most important thing for us to study the demos in the book now is to learn their design ideas and how to write code. They have the following attributes;

1. listSize (attribute): Use a listSize variable to save the number of elements in the list.
2. pos (attribute): The current position of the list, the index of the element.
3. dataStore (attribute): Initialize an empty array to save the number of elements. If we want to get a specific element in the list, we can use the pos attribute above; such as dataStore[pos];

All methods; explained in the following list, not introduced one by one.

2: How to implement the list class

According to the list abstract data type defined above, we can implement the following List class through the constructor prototype mode as follows.

Copy code The code is as follows:

function List() {
// Number of elements in the list
This.listSize = 0;

// What is the current position of the list
This.pos = 0;

// Initialize an empty array to save list elements
This.dataStore = [];

}

List.prototype = {
 
//Add element to the end of the list
append: function(element) {
      var self = this;
           self.dataStore[this.listSize] = element;
},

// Remove elements from the list
Remove: function(element) {
      var self = this;
      var curIndex = self.find(element);
If(curIndex > -1) {
                 self.dataStore.splice(curIndex,1);
​​​​​​—self.listSize;
             return true;
}
         return false;
},

// Find the element in the list and return the index
Find: function(element) {
      var self = this;
for(var i = 0,dataLen = self.dataStore.length; i < dataLen; i ) {
If(self.dataStore[i] == element) {
                   return i;
            }
}
         return -1;
},
 
// Return the number of elements in the list
length: function() {
          return this.listSize;
},

// Display elements in the list
toString: function(){
          return this.dataStore;
},

/*
* Insert an element after the specified element
* @param element current element
* @param elementAfter Insert the current element after this element
*/
​ insert: function(element,elementAfter){
      var self = this;
        var insertPos = self.find(elementAfter);
If(insertPos > -1) {
                 self.dataStore.splice(insertPos 1,0,element);
                self.listSize;
             return true;
}
         return false;
},
 
// Clear all elements in the list
Clear: function() {
          delete this.dataStore;
This.dataStore = [];
This.listSize = this.pos = 0;
},
// Determine whether the given element is in the list
contains: function(element) {
      var self = this;
for(var i = 0,ilen = self.dataStore.length; i < ilen; i ) {
If(self.dataStore[i] == element) {
                   return true;
            }
}
         return false;
},
// Move the current element in the list to the first position
Front: function(){
This.pos = 0;
},
// Move the current element in the list to the last position
End: function(){
This.pos = this.listSize - 1;
},
// Move the current position back one position
Prev: function(){
If(this.pos > 0) {
​​​​​​—this.pos;
}
},
// Move the current position forward one position
Next: function(){
If(this.pos < this.listSize - 1) {
This.pos;
}
},
// Return the current position of the list
CurPos: function(){
         return this.pos;
},
//Move the current position to the specified position
MoveTo: function(n) {
This.pos = n;
},
// Return the element at the current position
GetElement:function(){
          return this.dataStore[this.pos];
}
};

As above: Implement a list class, including as many methods as above. Of course, we can also extend some other methods to enrich the implementation of the list class. The most important thing is to learn the above coding method.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Explore the underlying principles and algorithm selection of the C++sort function Explore the underlying principles and algorithm selection of the C++sort function Apr 02, 2024 pm 05:36 PM

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

Compare complex data structures using Java function comparison Compare complex data structures using Java function comparison Apr 19, 2024 pm 10:24 PM

When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Improved detection algorithm: for target detection in high-resolution optical remote sensing images Improved detection algorithm: for target detection in high-resolution optical remote sensing images Jun 06, 2024 pm 12:33 PM

01 Outlook Summary Currently, it is difficult to achieve an appropriate balance between detection efficiency and detection results. We have developed an enhanced YOLOv5 algorithm for target detection in high-resolution optical remote sensing images, using multi-layer feature pyramids, multi-detection head strategies and hybrid attention modules to improve the effect of the target detection network in optical remote sensing images. According to the SIMD data set, the mAP of the new algorithm is 2.2% better than YOLOv5 and 8.48% better than YOLOX, achieving a better balance between detection results and speed. 02 Background & Motivation With the rapid development of remote sensing technology, high-resolution optical remote sensing images have been used to describe many objects on the earth’s surface, including aircraft, cars, buildings, etc. Object detection in the interpretation of remote sensing images

Application of algorithms in the construction of 58 portrait platform Application of algorithms in the construction of 58 portrait platform May 09, 2024 am 09:01 AM

1. Background of the Construction of 58 Portraits Platform First of all, I would like to share with you the background of the construction of the 58 Portrait Platform. 1. The traditional thinking of the traditional profiling platform is no longer enough. Building a user profiling platform relies on data warehouse modeling capabilities to integrate data from multiple business lines to build accurate user portraits; it also requires data mining to understand user behavior, interests and needs, and provide algorithms. side capabilities; finally, it also needs to have data platform capabilities to efficiently store, query and share user profile data and provide profile services. The main difference between a self-built business profiling platform and a middle-office profiling platform is that the self-built profiling platform serves a single business line and can be customized on demand; the mid-office platform serves multiple business lines, has complex modeling, and provides more general capabilities. 2.58 User portraits of the background of Zhongtai portrait construction

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

News recommendation algorithm based on global graph enhancement News recommendation algorithm based on global graph enhancement Apr 08, 2024 pm 09:16 PM

Author | Reviewed by Wang Hao | Chonglou News App is an important way for people to obtain information sources in their daily lives. Around 2010, popular foreign news apps included Zite and Flipboard, while popular domestic news apps were mainly the four major portals. With the popularity of new era news recommendation products represented by Toutiao, news apps have entered a new era. As for technology companies, no matter which one they are, as long as they master the sophisticated news recommendation algorithm technology, they will basically have the initiative and voice at the technical level. Today, let’s take a look at a RecSys2023 Best Long Paper Nomination Award paper—GoingBeyondLocal:GlobalGraph-EnhancedP

PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure Jun 03, 2024 am 09:58 AM

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

See all articles