The stack structure in JavaScript

Source: Internet
Author: User

1. Definition of stacks

The stack is a data structure similar to a list, which can be used to solve many programming problems, the stack is an efficient data structure, because the data can only be added or deleted at the top of the stack, so the operation is quick and easy to implement.

The stack is a special list of elements that can only be accessed at one end of the list, at the top of the Chan stack. A stack of dishes is the most common stack structure, only from the top of the plate, washing dishes can only be placed on the top. Stacks are called post-in, first-out data structures.

Because the stack has a post-in-first-out feature, any elements that are not at the top of the stack are inaccessible. To get the elements from the bottom of the stack, you must remove the above elements.

The operation of the stack has an element pressed into the stack and a pop-up stack. Press the stack using the push () method, and the pop-up stack uses the Pop () method. There is also a way to preview the top of the stack element, using the Pop () method although you can access the top element of the stack, but call the method after the stack of the top element will be permanently deleted. The Peek () method only spans the top element of the stack without deleting it.

To record the position of the top element of the stack, and also to mark where the new element can be added, we use the variable top, which decreases when the element is pressed into the stack, and the element is ejected from within the station.

Pop (), push (), Peek () method is the main three methods, while defining the clear () method can clear all the elements in the stack, the length property defines the number of elements in the stack, and defines an empty property to identify whether there are elements in the stack, However, using the length property can achieve the same purpose.

The code for the stack structure is as follows:

//using the array datastore to save the in-station element, the constructor initializes it to an empty array. //The variable top defines the position of the top of the stack and is constructed as 0, indicating that the stack starts at 0functionStack () { This. DataStore = [];  This. top = 0;  This. Push =push;  This. Pop =Pop;  This. Peek =Peek;  This. Clear =Clear;  This. length =length; //note the location of the + + operator, which is placed behind the this.top so that the new stack element is placed at the current position of top and the top is added 1, pointing to the next position    functionpush (Element) { This. datastore[ This. top++] =element; }    //returns the top element of the stack, minus 1 of top position    functionpop () {return  This. datastore[-- This. Top]; }    //The Peek () method returns an element of the top-1 position of the array, that is, the top element of a stack    functionPeek () {return  This. datastore[ This. top-1]; }    //set the value of top 0, that is, to empty a stack    functionClear () { This. top = 0; }    //The value that returns the top of the variable is the number of elements in the stack    functionLength () {return  This. Top; }}

Use the following code to verify the stack structure

var New Stack (); S.push ("David"), S.push ("Baymond"), S.push ("Bryan");d Ocument.writeln ( "Length:" + s.length ());d Ocument.writeln (S.peek ()); var popped = s.pop ();d Ocument.writeln ("The popped element is:" + popped);d Ocument.writeln (S.peek ()); S.push ("Cynthia");d Ocument.writeln (S.peek ()), S.clear ();d Ocument.writeln ("Length:" +  S.length ());d Ocument.writeln (S.peek ()), S.push ("Clayton");d Ocument.writeln (S.peek ());

The output is as follows:

Length:3
Bryan
The popped element Is:bryan
Baymond
Cynthia
length:0
Undefined
Clayton

2. Using the stack for the conversion of the binary

A stack can be used to convert a number from one to another, and the false assumption is to convert the number n to a number with the base B, as follows:

(1) The highest bit is n%b, the position is pressed into the stack

(2) using n/b instead of n

(3) Repeat (1), (2) until n equals 0, and no remainder

(4) Continue to pop the elements in the station, directly to the stack is empty, in turn, the elements are arranged, the converted number of the string form

Take a look at the following code, how to convert a number to 2 binary and 8 binary

functionMulbase (num,base) {vars =NewStack ();  Do{s.push (num%base); Num= Math.floor (num/= base); } while(num>0); varconverted = "";  while(S.length () >0) {converted+=S.pop (); }        returnconverted;}varnum = 32;varBase = 2;varNewnum =mulbase (num, base);d Ocument.writeln (Num+ "converted to base" + Base + "is" +newnum); Num= 125; base= 8; Newnum=mulbase (num, base);d Ocument.writeln (Num+ "converted to base" + Base + "is" + newnum);

The result of the final output is as follows:

Converted to base 2 are 100000 converted to base 8 is 175

3. Use the stack to judge a palindrome

A palindrome is a phenomenon in which a word, phrase, or number is the same as it was written from back to front and backwards. such as the word "Dad", "racecar" is a palindrome, if you ignore the space and punctuation, the following sentence is a palindrome, "a man, a plan, a Canal:panama", the number 1001 is a palindrome.

Use the stack to easily determine whether a character is a palindrome. We will get each character of the string in a left-to-right order into the stack, when all the characters are in the stack after the station saved a reversed string, the last character at the top of the stack, the first at the end of the stack. After the string is completely pressed into the station, a new string can be large by continuously popping each letter in the stack, which is exactly the opposite of the original string order. We just have to compare the two strings, and if they're equal, it means it's a palindrome. The code is as follows:

functionIspalindrome (word) {vars =NewStack ();  for(vari=0; i<word.length; ++i) {s.push (word[i]); }    varReword = "";  while(S.length () >0) {Reword+=S.pop (); }    if(Word = =reword) {        return true; }Else{        return false; }    }varWord = "Hello";if(Ispalindrome (Word)) {Document.writeln (Word+ "is a palindrome.");}Else{Document.writeln (Word+ "is not a palindrome");} Word= "Racecar";if(Ispalindrome (Word)) {Document.writeln (Word+ "is a palindrome.");}Else{Document.writeln (Word+ "is not a palindrome");}

The output results are as follows:

Hello is not a palindrome
Racecar is a palindrome.

4. Recursive implementation with stacks

Recursion is a very common algorithm, it is very easy to use the stack to implement recursion, for example, computing factorial can use recursive algorithm, as follows:

function factorial (n) {    if (n = = 0)        {return 1;    }     Else {        return n * factorial (n-1);    }}

Use the stack to simulate the factorial process, for example: First press 5 to 1 in the stack, then use a loop to give the number a pop-up to get the correct answer, the code is as follows:

function fact (n) {    varnew  Stack ();      while (n>1) {        s.push (n--);    }     var product = 1;      while (S.length () >0) {        *= s.pop ();    }     return product;} Document.writeln (Fact (5));

The results are as follows:

120

The stack structure in JavaScript

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.