JavaScript data structure and algorithm stack and queue Basics

Source: Internet
Author: User
Tags decimal to binary
In the object-oriented programming, the queue and stack methods are generally provided. For JS, we can implement array-related operations, to implement the queue and stack functions, see the following introduction. Learning cause

Once upon a visit to V2EX, I encountered such a post.
The mathematics is completely returned to the teacher. I want to learn some basic mathematics, which is probably high school. What books do I recommend?
The poster's university does not have a high number of courses, and he has been engaged in front-end work when he went out to work. I feel the lack of mathematics knowledge, so I want to make up for mathematics.
I looked at my post and thought it was very similar to me, because my major is not very high, and I also learned the front-end. I also feel the difficulty of lack of mathematical knowledge. At the same time, because my mathematical thinking is really not very good, so I decided to study the basic knowledge of mathematics and computer.
At that time, some people also said, "what data structures and algorithms do front-end require?", but I have my own opinions on this matter.
I don't think that the front-end does not need knowledge like algorithms. In my opinion, the front-end has a solid Computer Foundation, which is extremely beneficial to its own development. I want to be a programmer. Instead of a lifetime of elementary front-end and code farmers.
Let's encourage myself. After all, the Foundation determines the upper limit. In addition, I am really interested in computers, so I am very tired to learn, but it is also very happy. So I bought the book "Learning JavaScript data structures and algorithms" online, and started a preliminary study of data structures and algorithms in concert with the big talk Data Structure borrowed from the library.

Array Operations for ccipt

Next is the first part of the data structure, stack.
Stack is an ordered set that complies with the following First-In-First-Out principle (LIFO. Stack top is always the latest element.
For example, a stack is like a stack of books in a box. You need to take the books that you want to take out first. (Of course, you cannot take down the book first .)

Stack implementation in JavaScipt
First, create a constructor.

/*** Stack constructor */function Stack () {// simulate Stack var item = [] Using arrays;}

Stack requires the following methods:
Push (element (s): add several elements to the top of the stack
Pop (): removes and returns the top element of the stack.
Peek (): returns the top element of the stack.
IsAmpty: Check whether the stack is empty. If it is null, true is returned.
Clear: removes all elements from the stack.
Size: returns the number of elements in the stack.
Print: Display All content in the stack as a string
Implementation of the push Method
Note: A new element needs to be added to the stack. The element is located at the end of the queue. That is to say, we can use the push method of the array to simulate the implementation.

Implementation:

/*** Send the element to the stack and place it in the last position of the array * @ param {Any} element. The type is not limited */this. push = function (element) {items. push (element );};

Pop method implementation

Note: The top element of the stack needs to be popped up and the pop-up value is returned. You can use the pop method of the array to simulate the implementation.
Implementation:

/*** Top stack element * @ return {Any} returns the value to be popped up */this. pop = function () {return items. pop ();};

Implementation of the peek Method
Views the top element of the stack, which can be achieved using the array length.
Implementation:

/*** View the top stack element * @ return {Any} return the top stack element */this. peek = function () {return items [items. length-1];}

Implementation of other methods
Note: The first three are the core of the stack method, and the remaining methods are listed here at one time. The queue mentioned below will overlap with this part.
Implementation:

/*** Determine whether the stack is empty * @ return {Boolean} returns true if the stack is empty. If the stack is not empty, returns false */this. isAmpty = function () {return items. length = 0};/*** clear all content in the stack */this. clear = function () {items = [] ;};/*** return stack length * @ return {Number} stack length */this. size = function () {return items. length ;};/*** display all content in the stack with strings */this. print = function () {console. log (items. toString ());};

Practical Application

Stack has many practical applications. There is a decimal to binary function in the book. (If you do not know how to calculate binary, Baidu can) The following is the source code of the function.
The principle is to input the number to be converted, divide it by two and take the integer. Finally, we use the while loop to splice all the numbers in the stack into strings for output.

/*** Convert a 10-digit Number to a 2-digit Number * @ param {Number} decNumber the 10-digit Number to be converted * @ return {Number} The 2-digit Number after conversion number */function pideBy2 (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 ;};

So far, stack learning has come to an end. Because there are many comments in the source code, we will not post the source code content here.

Queue

The queue and stack are very similar data structures. The difference is that the queue is FIFO (First In First Out.
For example, buy tickets in queue at the railway station first come first served. (Not included in the queue) Is it easy to understand ~

Queue implementation in JavaScipt

The implementation of queues is similar to that of stacks. The first is the constructor:

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

The following methods are required for Queues:
Enqueue (element (s): add several items to the end of the queue
Dequeue (): removes the first entry (that is, the first entry) of the queue)
Front (): returns the first element of the queue, that is, the newly added one.
Other methods are the same as those in the queue.

Enqueue method implementation

Note: add several items to the end of the queue.
Implementation:

/*** Push the element to the end of the queue * @ param {Any} ele the element to push into the queue */this. enqueue = function (ele) {items. push (ele );};

Dequeue method implementation

Note: This is the first option to remove a queue.
Implementation:

/*** Bring up the first element in the queue * @ return {Any} to return the pop-up element */this. dequeue = function () {return items. shift ()};

Front method implementation

Note: return the first element of the queue, that is, the newly added one.
Implementation:

/*** View the first element of the queue * @ return {Any} return the first element in the queue */this. front = function () {return items [0];};

The above three methods are the core methods of the data structure of the queue. Actually, it is easy to understand.

Practical Application
The book is a small drum-and-teaser game. The principle is that the element pops up in the queue when it loops to the corresponding position. The last thing left behind is the winner.
The source code is as follows:

/*** Drum-and-teaser games * @ param {Array} nameList participant list * @ param {Number} num position to be popped up in the loop * @ return {String} return winner (the final winner) */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 (); c Onsole. log (eliminated + "Get out! ")} Return queue. dequeue ()}

The learning of the queue has come to an end. The next phase will introduce another data structure: linked list.

Feelings

Many times it is confusing to read a book and directly read an introduction to algorithms or some data structures. Later, I found that reading a book starts from what I can understand. It is a suitable learning method.

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.