JavaScript Data Structure Learning array, stack and queue, data structure stack and queue

Source: Internet
Author: User

JavaScript Data Structure Learning array, stack and queue, data structure stack and queue

Preface

A Data Structure is a set of relationships. Yes, it is a set of one or more specific relationships between data elements.

Common data structures include:

Array, queue, heap, stack, linked list, tree, graph, and hash)

This article mainly introduces arrays, stacks, and queues. Let's take a look at the details.

I. Array

Arrays are the most commonly used data structures. In JavaScript, arrays are dynamically allocated. Here I will not introduce all the methods of arrays in JavaScript, we will talk about the methods used in the direction of data structure.

Create and initialize Arrays

// Create an empty array var Array = new array (); // [] // initialize the Array var array = new Array (1, 2, 3); var array = Array. of (, 3); // ES6 method // [, 3] // create an array of 5 var Array = new array (); // ES6 method // [undefined, undefined] // assign var array = new Array () to the array; array [0] = 1; array [1] = 2; array [2] = 3; // [1, 2, 3]

Add Element

Add elements to the array

Var number = [1, 2, 3]; number [number. length] = 4; // [1, 2, 3, 4] // or var number = [1, 2, 3]; number. push (4); // [1, 2, 4]

Add elements to the front of the array

var number = [1,2,3];number.unshift(0);//[0,1,2,3]number.unshift(-2,-1);//[-2,-1,0,1,2,3]

Insert elements to any position in the array

Use the splice Method

// Add 2,3, 4var number = [, 6]; number. splice (, 4) After Index 1; // [,]

Delete Element

Delete first

var number = [1,2,3];number.shift();//[2,3]

Delete any location

Use the splice method to delete any element in the array

Var numebr = [1, 2, 3, 4, 5, 6]; // if you want to delete the element 3number. splice (); // [, 5, 6] // if you want to delete element 4, 5number. splice (3, 2 );

Sort

Reverse Order

var number = [3,2,1];number.reverse();//[1,2,3]

Natural sorting

var numebr = [2,3,4,1,3,7];number.sort();//[1,2,3,3,4,7]

Custom sorting

This custom sorting is similar to implementing the comparator interface in java. It is very useful.

var number = [4,5,6,7,1,2,3,8,9,10,11,12,13];number.sort();//[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

It seems a little wrong. What we should want is
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. In this case, we use custom sorting to solve this problem.

var number = [4,5,6,7,1,2,3,8,9,10,11,12,13];function compare(a,b){ if(a < b){ return -1; } if(a > b){ return 1; } return 0;}number.sort(compare);//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

This is just the easiest way to sort arrays of any object type. For example, the object Person has the name and age attributes, and we want to sort by age

Var friends = [{name: 'Li Chen ', age: 40}, {name: 'fan Bingbing', age: 35}]; function comparePerson (a, B) {if (. age <B. age) {return-1;} if (. age> B. age) {return 1 ;}return 0 ;}friends. sort (comparePerson); // [{name: 'fan Bingbing ', age: 35}, {name: 'Li Chen', age: 40}]

Search

The indexOf method returns the index of the first element that matches the parameter. lastIndexOf returns the index of the last element that matches the parameter.

var number = [1,3,4,3,56,6,7,4];number.indexOf(3);//1number.lastIndexOf(3)//3

Ii. Stack

Stack is an ordered set that follows the following LIFO principles. Newly Added or elements to be deleted are stored at the end of the stack, called the stack top, and the other end is called the stack bottom. In the stack, new elements are close to the top of the stack, and old elements are close to the bottom of the stack. In JavaScript, both variable saving and function calling are stored in stacks.

First, create a class to represent a stack. A data structure is required to store the elements in the stack. Here we will select the newly learned array:var items = [];
Next, we will declare some methods for our Stack:

  1. push(elements(s)): Add one (or several) new elements to the top of the stack.
  2. pop(): Removes the elements at the top of the stack and returns the removed elements.
  3. peek(): Gets the elements at the top of the stack and does not make any modifications to the stack.
  4. isEmpty(): If the stack does not contain any element, true is returned; otherwise, false is returned;
  5. clear(): Clear Stack
  6. size() : Returns the number of stack elements.

If you read the array carefully in the previous section, I believe it is very easy to implement a stack using JavaScript. Here we will directly introduce the code. We don't need a method or a method to explain it.

function Stack(){ var items = []; this.push = function(element){ items.push(element); } this.pop = function(){ return items.pop(); } this.peek = function(){ return items[items.length-1]; } this.isEmpty = function(){ return items.length === 0; } this.size = function(){ return items.length; } this.clear = function(){ items = []; } this.print = funciton(){ console.log(items.toString()); }}

3. Queue

A queue is a group of Ordered items that follow the FIFO principle. Add new elements to the end of the queue and remove the elements from the top. The newly added element is at the end of the queue.

A common example in real life is queuing.
In computer science, a common example is to print a queue. The printed documents are printed first.

Create a queue

Create a class to represent a queue. The required data structure is also an array var items = [];

Declare available methods:

  • enqueue(element(s)): Add one or more new items to the end of the team
  • dequeue(): Remove the first (that is, the first) item in the queue and return the removed element.
  • front(): Returns the first element in the queue.
  • isEmpty() : If the queue does not contain elements, true is returned. Otherwise, false is returned.
  • size(): Returns the number of elements in the queue.

Complete Queue class

function Queue(){ var items = []; this.enqueue = function(element){ items.push(element); } this.dequeue = function(){ return items.shift(); } this.front = function(){ return items[0]; } this.isEmpty = function(){ return items.length === 0; } this.clear = function(){ items = []; } this.size = funciton(){ return items.length; } this.print = function(){ console.log(items.toString()); }}

Priority queue

In a priority queue, an element is given a priority. When an element is accessed, the element with the highest priority is deleted first. The priority queue has the highest first-in-first-out behavior characteristics. For example, the hospital's emergency room gives priority to the patient (this priority can indicate the severity of the illness), and the patient with the highest priority gets the first treatment.

There are two options for implementing a priority queue:

  • Set priority and add elements in the correct position;
  • Add elements by column operation and remove them by priority.

Here we use the first one.

Function PriorityQueue () {var items = []; funciton QueueElement (element, priority) {this. element = element; this. priority = priority;} function comparePriority (a, B) {if (. priority> B. priority) {return 1;} if (. priority <B. priority) {return-1;} return 0;} this. enqueue = funciton (element, priority) {var queueElement = new QueueElement (element, priority); items. push (queueElement); items. sort (comparePriority);} // other methods are the same as the default Queue Implementation}

Of course, there are many implementation methods for this enqueue. I am not the most efficient, but it is easy to understand. Sort the inserted elements in order of priority.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.