JavaScript data structure and algorithm stack and queue _ basics

Source: Internet
Author: User
Tags data structures decimal to binary

Learning causes

Once in a stroll v2ex, encountered such a post.
Mathematics completely back to the teacher, want to learn some basic mathematics, probably high school degree, what book recommended?
Post the landlord University does not have a high number of courses, go out to work has been engaged in the front-end work. Feel the lack of knowledge of mathematics, so I want to make up a math supplement.
Look at the post, feeling and I very much like, because my major is not open high number, I learned is also the front. Also felt the lack of mathematical knowledge brought about by the predicament. At the same time because their mathematical thinking is not very good, so decided to work hard to cram mathematics and computer basic knowledge.
At that time, some people said: "What data structure and algorithm front-end needs," but I have my own opinion on this matter.
I do not think that the front end does not need the knowledge of the algorithm, in my view the front end has a solid computer base, for its own development is extremely advantageous. I want to be a programmer. Rather than a lifetime of primary front end and code farmer.
It is a kind of encouragement to oneself. After all, the basis of the decision ceiling, coupled with their own computer is really interested, so learn even if very tired, but also very happy. So go online to buy the "learning JavaScript data structure and algorithm" this book, with the library to borrow the "big talk data Structure", began the data structure and algorithm preliminary study.

Array operation of Javascipt

Next is the data structure of the first part of the stack.
A stack is an ordered set that complies with the LIFO principle (LIFO, which is all called last in-first). The top of the stack is always the newest element.
For example, a stack is like a stack of books in a box. You have to take the book below to get the book off the top. (Of course, you can't take the following book first.) )

Implementation of Stack in Javascipt
First, create a constructor.

/**
 * Stack's constructor
 /function
stack () {

 ///array to simulate stack
 var item = [];
}

Stacks need to have the following methods:
Push (Element (s)): Add several elements to the top of the stack
Pop (): Remove and return to top of stack element
Peek (): Returns the top element of the stack
Isampty: Check stack is empty, NULL returns True
Clear: Remove all elements from the stack
Size: Returns the number of elements in the stack.
Print: Displays all content in the stack as a string
Implementation of Push method
Note: You need to add a new element to the stack, where the element position is at the end of the queue. In other words, we can simulate the implementation by using the push method of the array.

Realize:

/**
 * The element is fed into the stack, placed in the last
 * @param {any} element of the array, unrestricted type
 *
/This.push = function (Element) {
 Items.push (element);

The realization of pop method

Note: You need to eject the top element of the stack and return the value that was ejected. You can use an array of pop methods to simulate the implementation.
Realize:

/**
 * Pop-up stack top element
 * @return {any} returns the value that is ejected */
this.pop = function () {return
 items.pop ();
};

The realization of Peek method
Description: View the top of the stack, you can use the length of the array to implement.
Realize:

/**
 * View stack top element
 * @return {any} back to top element
/This.peek = function () {return
 items[items.length-1];
}

Implementation of the remaining methods
Description: The first three are the core of the stack method, and the remaining methods are listed at once. Because the queue to be discussed below will have a great overlap with this part.
Realize:

/**
 * Determine if stack is empty
 * @return {Boolean} returns True if the stack is empty, returns false *
/this.isampty = function () {return
 Items.length = = 0
};

/**
 * Empty stack all content
/this.clear = function () {
 items = [];
};

/**
 * Returns the length of the stack
 * @return {number} stack length * *
this.size = function () {return
 items.length;
};

/**
 * Displays all contents of the stack in a string/
this.print = function () {
 console.log (items.tostring ());
};

Practical application

The actual application of the stack is more, the book has a decimal to binary function. (Do not know how to calculate the binary system can be Baidu) The following is the source code of the function.
The principle is to enter the number you want to convert, dividing by two and rounding. Finally, the while loop is used to stitch all the numbers in the stack into string output.

/** * Converts a 10-digit number to
 2-digit
 * @param {number} Decnumber the      converted 2
-digit number of the 10-binary number you want to convert * * * @return function DivideBy2 (decnumber) {

 var remstack = new Stack (),
  rem,
  binarystring = ';

 while (Decnumber > 0) {
  rem = Math.floor (decnumber% 2);
  Remstack.push (REM);
  Decnumber = Math.floor (DECNUMBER/2);
 }

 while (!remstack.isampty ()) {
  binarystring = = Remstack.pop (). toString ()
 ;

 return binarystring;
};

In this case, the stack of learning will come to an ending. Because there are more annotations in the source code, the source code content is not posted here.

Queue

Queues and stacks are very similar data structures, except that queues are FIFO (Fifo:first in first).
For example: Train station in line to buy tickets, first arrived first. (not counting the queue), is not very good understanding ~

Implementation of Javascipt Squadron column

The implementation of the queue is similar to the stack. The first remains the constructor:

/**
 * Queue constructor
 /function
queue () {
 var items = [];
}

Queues need to have the following methods:
Enqueue (Element (s)): Add several items to the end of the queue
Dequeue (): Removes the first item (that is, the top item) from the queue
Front (): Returns the first element of the queue, which is the newly added
The remaining methods are the same as the queues

The realization of Enqueue method

Description: Adds several items to the tail of the queue.
Realize:

/**
 * Pushes the element into the tail
 of the queue * @param {any} ele the element to be pushed into the queue/
this.enqueue = function (ele) {
 items.push (ele);
};

The realization of Dequeue method

Description: Removes the first item from the queue.
Realize:

/**
 * Eject the first element in the queue
 * @return {any} returns the element that is
 ejected
/this.dequeue = function () {return
 items.shift ( )
};

The realization of front method

Description: Returns the first element of the queue, which is the newly added one.
Realize:

/**
 * View the first element of the queue
 * @return {any} returns the first element of the queue
/This.front = function () {return
 items[0];

The above three methods are the core method of the data structure of the queue. In fact, very good understanding.

Practical application
The book is a little game of drumming and spreading flowers. The principle is that the queue pops up the element when it loops to the appropriate position. The last thing left is a winner.
The source code is as follows:

/**
 * The little game of playing drums
 * @param {Array} namelist participant List
 * @param {number} num   in the loop where to be ejected
 * @return {String}     returns the winner (that is, the last surviving)/
function Hotpotato (namelist, num) {
 var queue = new Queue ();

 for (var i = 0; i < namelist.length i++) {
  queue.enqueue (namelist[i]);

 var eliminated = ';

 while (Queue.size () > 1) {for
  (var i = 0; i < num; i++) {
   queue.enqueue (Queue.dequeue ());
  }

  eliminated = Queue.dequeue ();
  Console.log (Eliminated + "Get out!")
 }

 Return Queue.dequeue ()
}

The study of the queue will come to an ending. The next issue will cover another type of data structure: linked lists.

Feelings

Most of the time reading, directly to see the algorithm introduction or some data structure of the book, are very confused. Later found that reading from their own can understand the beginning of the more than the right way to learn.

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.