JavaScript data structures and algorithms stack and queue, data structures and algorithms

Source: Internet
Author: User
Tags decimal to binary

JavaScript data structures and algorithms stack and queue, data structures and algorithms

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 () {

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

The stack needs to have the following methods:
push (element (s)): add a few elements to the top of the stack
pop (): remove and return the top element of the stack
peek (): return the top element of the stack
isAmpty: check if the stack is empty, return true if empty
clear: remove all elements from the stack
size: Returns the number of elements in the stack.
print: display all contents of the stack as a string
Implementation of push method
Explanation: New elements need to be added to the stack, and the element position is at the end of the queue. In other words, we can use the push method of the array to simulate the implementation.
achieve:

/ **
 * Push the element onto the stack and place it in the last position of the array
 * @param {Any} element Accepted element, no restriction on type
 * /
this.push = function (element) {
 items.push (element);
};
Implementation of pop method

Explanation: You need to pop the top element of the stack and return the popped value. You can use the array pop method to simulate the implementation.
achieve:

/ **
 * Pop the top element of the stack
 * @return {Any} returns the popped value
 * /
this.pop = function () {
 return items.pop ();
};
Implementation of peek method
Explanation: Viewing the top element of the stack can be achieved by the length of the array.
achieve:

/ **
 * View the top element of the stack
 * @return {Any} returns the top element of the stack
 * /
this.peek = function () {
 return items [items.length-1];
}
Implementation of the remaining methods
Explanation: The first three are the core of the stack method, and the remaining methods are listed here at once. Because the queue to be described below will have a great overlap with this part.
achieve:

/ **
 * Determine whether the stack is empty
 * @return {Boolean} true if the stack is empty, false if not
 * /
this.isAmpty = function () {
 return items.length === 0
};

/ **
 * Clear all contents in the stack
 * /
this.clear = function () {
 items = [];
};

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

/ **
 * Display all contents of the stack as a string
 * /
this.print = function () {
 console.log (items.toString ());
};

Practical application
There are many practical applications of the stack. There is a function of decimal to binary in the book. (If you don't know how to calculate binary, you can Baidu) The following is the source code of the function.
The principle is to input the number to be converted, continuously dividing by two and rounding. And finally use a while loop to splice all the numbers in the stack into a string output.

/ **
 * Convert decimal numbers to binary numbers
 * @param {Number} decNumber Decimal number to be converted
 * @return {Number} The converted binary number
 * /
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;
};

At this point, the learning of the stack comes to an end. Because there are many comments in the source code, the content of the source code will not be posted here.

queue
Queue and stack are very similar data structures, the difference is that the queue is first in first out (FIFO: First In First Out).
For example: train stations line up to buy tickets, first come first. (It's not a cut in the queue) Is it easy to understand ~
Implementation of queue in JavaScipt
The implementation of the queue is very similar to the stack. The first is still the constructor:

/ **
 * Queue constructor
 * /
function Queue () {
 var items = [];
}
The queue needs to have the following methods:
enqueue (element (s)): add several items to the end of the queue
dequeue (): remove the first item in the queue
front (): returns the first element of the queue, which is the newly added one
The remaining methods are the same as the queue
Implementation of enqueue method
Explanation: Add several items to the end of the queue.
achieve:

/ **
 * Push the element to the end of the queue
 * @param {Any} ele The element to be pushed into the queue
 * /
this.enqueue = function (ele) {
 items.push (ele);
};
Implementation of the dequeue method
Explanation: Remove the first item in the queue.
achieve:

/ **
 * Pop the first element in the queue
 * @return {Any} returns the popped element
 * /
this.dequeue = function () {
 return items.shift ()
};
Front method implementation
Explanation: Returns the first element of the queue, which is the newly added one.
achieve:

/ **
 * View the first element of the queue
 * @return {Any} returns the first element in the queue
 * /
this.front = function () {
 return items [0];
};
The above three methods are the core methods of the queue data structure. Actually, it's easy to understand.
Practical application
The book is a game of drumming and passing flowers. The principle is that when looping to the corresponding position, the queue pops up that element. The last thing left is the winner.
The source code is as follows:

/ **
 * A game of drumming and passing flowers
 * @param {Array} nameList participant list
 * @param {Number} num The position to be popped in the loop
 * @return {String} returns the winner (that is, the last one who survived)
 * /
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 learning of the queue has come to an end. The next issue will talk about another data structure: linked lists.
Feelings

Many times reading books, directly reading the introduction to algorithms or some data structure books, are very confused. It was later discovered that reading from the beginning can be understood by oneself, and from shallow to deep is the suitable learning method for oneself.

Articles you may be interested in:
C # data structure and algorithm reveals five stacks and queues
Analyze how to use two stacks to implement queues
Python implementation of stack and queue method
Implementation method of queue and stack in Go language
In-depth JavaScript advanced programming objects and arrays (stack method, queue method, reorder method, iteration 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.