JavaScript stacks and queues detailed tutorials

Source: Internet
Author: User
Tags arrays first string numeric value sorts trim

javascript: Stacks


A list is the most natural way to organize data. A stack is a data structure similar to a list that can be used to solve many problems in the computer world. Stacks are an efficient data structure because the data can only be added or removed from the top of the stack, so this is quick and easy to implement. Stacks are used in all aspects of the programming language, from expression evaluation to processing function calls.

One: The operation of the stack

A stack is a special list of elements within a stack that can only be accessed through one end of the list, which is called the top of the stack. A stack of dishes in the café is an example of the most common stack in the real world. They can only be taken from the top of the plate, and after the dishes are washed, they can only be stacked on top of the stack. A stack is referred to as a LIFO,LAST-IN-FIRST-OUT data structure.

Because the stack has the characteristics of the first out, all the elements are not at the top of the stack can not access, in order to get the bottom of the stack elements, must choose to take off the above elements. As shown in figure:




The two main operations for stacks are to push an element into the stack and pop a stack of elements into the stack using the push () method. The out stack uses the Pop () method.





Another common operation is to preview the elements at the top of the stack. The Pop () method can access the elements at the top of the stack, but after the method is invoked, the elements on top of the stack are permanently deleted from the stack. The Peek () method returns only the top element of the stack without deleting it.





To record the position of the top element of the stack, but also to mark where to add new elements. We use the top of the variable, when the element is pressed into the stack, the variable is enlarged and the variable is reduced when the element is ejected from the stack.








Push (), pop () and peek () are the three main methods of operation of the stack, but there are other methods and properties on the stack. The clear () method clears all elements within the stack, and the length property records the number of elements in the stack. We also define a empty property that indicates if there are any elements in the stack (use length to achieve the same purpose).








Second: The implementation of the stack:





To implement a stack, it is imperative to decide on the underlying data structure that stores it. The array is used here.





We implement the constructor of the stack class to start with:








function Stack () {


This.datastore = [];


this.top = 0;


This.push = push;


This.pop = Pop;


This.peek = peek;


}











We use array datastore to save the elements in the stack, constructor to initialize it to an empty array, where the top of the variable tops records the position of the stack, and the constructed function is initialized to 0, indicating that the top of the stack is 0 at the beginning of the array. If an element is pressed into the stack, the value of the variable changes.





To implement the push () method first. When you press a new element into the stack, you need to save it in the position of top in the array, and then add top 1. Let it point to the next empty position in the array.





function push (Element) {


this.datastore[this.top++] = element;


}





In particular, note the position of the + + operator, which is placed behind the this.top, so that the new stack element is placed at the top of the current value of the position, and then the top value plus 1. Point to the next location.





The Pop () method is just the opposite of the push () method, which returns the top element of the stack while reducing the value of the maximum variable to 1.





function Pop () {


return This.datastore[--this.top]


}





The Peek () method returns the element at the top-1 position of the array, which is the top element of the stack:





function Peek () {


return This.datastore[this.top-1]


}





If the peek () method is invoked on an empty array, the result is undefined. This is because the stack is empty and the top of the stack has no elements.





Sometimes you need to know that there are multiple elements stored in the stack. The length () method returns the number of elements in the stack by returning the top value of the variable.





function Length () {


Return This.top


}





Finally, you can set the top value to 0 to easily empty a stack.





function Clear () {


this.top = 0;


}





Attached: test code








function Stack () {


This.datastore = [];


this.top = 0;


This.push = push;


This.pop = Pop;


This.peek = peek;


This.clear = clear;


this.length = length;


}





Press into Stack


function push (Element) {


this.datastore[this.top++] = element;


}





Pop-up stacks


function Pop () {


return This.datastore[--this.top]


}





Stack top Element


function Peek () {


if (this.datastore[this.top-1] = = undefined) {


Return "None"


// }


return This.datastore[this.top-1]


}





Empty stack


function Clear () {


this.top = 0;


}





Number of stack elements


function Length () {


Return This.top


}





var Newstak = new Stack ();


Newstak.push ("Niu Niu")


Newstak.push ("peas")


Newstak.push ("Floral")





Console.log (Newstak.length ())


Console.log (Newstak.peek ())





var poped = Newstak.pop ();


Console.log (poped);


Console.log (Newstak.peek ());//


Newstak.clear ();





Console.log (Newstak.length ())


Console.log (Newstak.peek ());


Newstak.push ("Sheep and sheep");


Console.log (Newstak);


Console.log (Newstak.peek ());











three. Using the Stack class





There are some issues that are especially suitable for use with stacks, first with a few examples:





1. Conversion between the numbering





You can use stacks to convert a number from one value to another. A false idea converts a number n to a number with a base of B. The implementation conversion algorithm is as follows:





1. The highest bit is n% B, press this bit into the stack


2. Use n/b instead of n


3. Repeat steps 1 and 2 until n equals 0, and there is no remainder.


4. Continue to pop the elements in the stack until the stack is empty. By arranging these elements in turn, you get the string form of the converted digits.


(This algorithm only levies a cardinality of 2-9)





Using stacks, it's easy to implement the algorithm in JavaScript, and here's the definition of the function that converts numbers to numbers from two to nine.








function mulbase (num, base) {


var s = new Stack ();


do {


S.push (num% base);


num = Math.floor (num/= base);


while (num > 0);


var converted = "";


while (s.length () > 0) {


Converted + + S.pop ()


}


return converted;


}











The following shows the use of this method to convert numbers to binary and octal numbers.


Converts a number to binary and octal.








function mulbase (num, base) {


var s = new Stack ();


do {


S.push (num% base);


num = Math.floor (num/= base);


while (num > 0);


var converted = "";


while (s.length () > 0) {


Converted + + S.pop ()


}


return converted;


}





var num = 32;


var base = 2;





var newnum = mulbase (num, base);


Converted to base 2 is 100000


Console.log (num + "converted to base" + Base + "is" + newnum)





num = 125;


base = 8;





var newnum = mulbase (num, base);





Converted to base 8 is 175


Console.log (num + "converted to base" + Base + "is" + newnum)











2. A palindrome.








A palindrome is a phenomenon in which a word, phrase, or number is the same as when it is written and written backwards. For example: The word "Dad", "racecar" is a palindrome. If you ignore spaces and punctuation, the following sentence is also a palindrome. "A man, a plan, a Canal:panama"; The number 1001 is also a palindrome.





Using stacks, you can easily determine whether a string is a palindrome. Each character we get from the string is pressed into the stack in order from left to right. When the character of the string is in the stack, a reversed string is saved inside the stack, the last string is at the top of the stack, and the first string is at the bottom of the stack.





After the string is completely pressed into the stack, a new string is obtained by continuing to eject each letter in the stack, which is exactly the opposite of the original string order. We just need to compare two strings. If they are equal, they are a palindrome.





Example: To determine whether a given string is a palindrome.








function Ispalindrome (word) {


var s = new Stack ();


for (var i = 0; i < word.length; ++i) {


S.push (Word[i]);


}


var word = "";


while (s.length () > 0) {


RWord + + s.pop ();


}


if (Word = = RWord) {


return true;


}


else {


return false;


}


}





var word = "Hello";


if (Ispalindrome (word)) {


Console.log (Word + "is palindrome");


} else {


Console.log (Word + "not palindrome")


}





var word = "racecar";


if (Ispalindrome (word)) {


Console.log (Word + "is palindrome");


} else {


Console.log (Word + "not palindrome")


}











Third: recursive demo;





Stacks are commonly used to implement programming languages, using stacks to achieve recursion is an example (here only using stacks to simulate the recursive process).





To demonstrate how to implement recursion using stacks, consider the following recursive definition of factorial. First, let's see how the 5 factorial is defined.





5! = 5*4*3*2*1 = 120





Here is a recursive function that calculates the factorial of any number








function factorial (n) {


if (n = = 0) {


return 1;


} else {


return n * Factorial (n-1)


}


}














Using stacks to simulate the factorial of 5, return 120





Use stacks to simulate computing 5! Of the process, first the number from 5 to 1 into the stack, and then use a loop, the number pop up to multiply, you get 5 factorial








function fact (n) {


var s = new Stack ();


while (n > 1) {


S.push (n--);


}





var product = 1;


while (s.length () > 0) {


Product *= S.pop ()


}





return product;


}











javascript: Queues




A queue is a list, except that the queue inserts elements at the end and deletes the elements at the head of the team. Queues are used to store data in sorted order. Advanced first out. This is not the same as the stack, in the stack, the last element of the stack is treated preferentially. The queue can be imagined as a bank queue for business, the queue in the first person to deal with the business, the others can only be queued until their turn.





A queue is a first-in, first-out (FIFO) data structure. Queues are used in many places. such as submitting the operating system to perform a series of processes. Print a task pool, and so on. Some simulation systems are used to simulate queues of customers in banks or grocery stores.





One, the operation of the queue.





The two main operations of a queue are to insert new elements into the queue and to delete the elements in the queue. The insert operation is also called the team. Deleting elements is also called making teams. The team is to insert a new element at the end, which is the element that deletes the team head.





Another operation of the queue is to read the elements of the team head, this operation is called PEEK (). This action returns the element of the team header, but does not remove it from the queue. In addition to reading the elements of the team head, we want to know how many elements there are in the queue, you can use the length property to satisfy the requirements, and you want to empty all the elements in the queue. Can be implemented using the clear () method.





two, an array implementation of the queue.





Using arrays to implement queues looks logical. Arrays in JavaScript have advantages that are not available in other programming languages, and the push () of an array can add elements to the end of the array, and the shift () method of the array can delete the first element of the array.





The push () method inserts its arguments into the first open position in the array, which is always at the end of the array, even if it is an empty array.





names = [];


Names.push ("Cny");


Names.push ("Jen");


Console.log (names);//["Cny", "Jen"]





Then use the shift () method to delete the first element of the array:





Names.shift ();


Console.log (names);//["Jen"]





Ready to start implementing the Queue class. Start with the constructor:








function Queue () {


This.datastore = [];


This.enqueue = Enqueue;


This.dequeue = dequeue;


This.front = Front;


This.back = back;


this.tostring = toString;


This.empty = empty;


}











The Enqueue () method adds an element to the end of the team:





function Enqueue (Element) {


This.dataStore.push (Element)


}





Dequeue method to delete a team head element





function Dequeue () {


return This.dataStore.shift ();


}





You can read the elements of the team head and the end of the team using the following methods








function Front () {


return this.datastore[0];


}





function back () {


return This.datastore[this.datastore.length-1]


}











You also need the ToString () method to display all the elements within the queue








function toString () {


var retstr = "";


for (var i = 0; i < this.dataStore.length; ++i) {


Retstr + = This.datastore[i] + "\ n";


}


Return RETSTR


}











Finally, a method is needed to determine whether the queue is empty








function empty () {


if (This.dataStore.length = = 0) {


return true;


} else {


return false;


}


}











Definition and testing of the queue class








function Queue () {


This.datastore = [];


This.enqueue = Enqueue;


This.dequeue = dequeue;


This.front = Front;


This.back = back;


this.tostring = toString;


This.empty = empty;


}





Add an element to the end of the team


function Enqueue (Element) {


This.dataStore.push (Element)


}





Delete the elements of a team head


function Dequeue () {


return This.dataStore.shift ();


}





function Front () {//Read the elements of the team head and the end of the team


return this.datastore[0];


}


function back () {////reads the elements of the team head and the end of the team


return This.datastore[this.datastore.length-1]


}





Show all elements within a queue


function toString () {


var retstr = "";


for (var i = 0; i < this.dataStore.length; ++i) {


Retstr + = This.datastore[i] + "\ n";


}


Return RETSTR


}





Whether the queue is empty


function empty () {


if (This.dataStore.length = = 0) {


return true;


} else {


return false;


}


}








Test program





var q = new Queue ();


Q.enqueue ("Me");


Q.enqueue ("her");


Q.enqueue ("his");


Console.log (Q.tostring ());


Q.dequeue ();


Console.log (Q.tostring ());





Console.log ("The first element is:" + q.front ());


Console.log ("Last element is:" + q.back ())








third, the use of queues, square dance and partner assignment issues





As we mentioned earlier, we often use queues to simulate people in line. Below, we use the queue to simulate the people who jump the square dance. When men and women came to the dance floor, they lined up in two teams according to their sex. When there is room in the dance floor, the first person in the two queues is a partner. The people behind them each moved forward, forming a new team head. When a new partner enters the dance floor, the host yells out their names. When a pair of partners out of the dance floor, and the two teams have no one team, the moderator will tell the situation to everyone.





To simulate this, we store the names of men and women in a text file.








Female Xiao Li


Male blessing come


Male strong son


Man Li Yong


Female Xiaomei


Male to Fu


Girl ally.


Male sail


Man Wen


Male lik


Female Nana











Each dancer's information is saved in a dancer object:





function dancer (name, sex) {


THIS.name = name;


This.sex = sex;


}





We need a function that reads the dancer's information into the program.








function getdancers (males, females) {


var names = _names.split ("\ n");


var names = _names.split ("* *");


for (var i = 0; i < names.length; ++i) {


Names[i] = Names[i].trim ();


}





for (var i = 0; i < names.length; ++i) {


var dancer = Names[i].split ("");


var sex = dancer[0];


var name = dancer[1];


if (sex = = "female") {


Females.enqueue (New dancer (name, sex));


} else {


Males.enqueue (New dancer (name, sex))


}


}


}











This function points the dancers to different queues according to their sex.





The next function will make the male and female partner and announce the pairing result:








function dance (males, females) {


Console.log ("This group of Partners is:")


while (!females.empty () &&!males.empty ()) {


person = Females.dequeue ();


Console.log ("Female dancer is" + person.name);





person = Males.dequeue ();


Console.log ("Male dancer is" + person.name);


}


}











We may have modified the program to show the number of men in the queue, and there is currently no way to display the number of elements in the queues. Join now





function count () {


return this.dataStore.length;


}





Comprehensive test:








function Queue () {


This.datastore = [];


This.enqueue = Enqueue;


This.dequeue = dequeue;


This.front = Front;


This.back = back;


this.tostring = toString;


This.empty = empty;


This.count = count;


}





Add an element to the end of the team


function Enqueue (Element) {


This.dataStore.push (Element)


}





Delete the elements of a team head


function Dequeue () {


return This.dataStore.shift ();


}





function Front () {//Read the elements of the team head and the end of the team


return this.datastore[0];


}


function back () {////reads the elements of the team head and the end of the team


return This.datastore[this.datastore.length-1]


}





Show all elements within a queue


function toString () {


var retstr = "";


for (var i = 0; i < this.dataStore.length; ++i) {


Retstr + = This.datastore[i] + "\ n";


}


Return RETSTR


}





Whether the queue is empty


function empty () {


if (This.dataStore.length = = 0) {


return true;


} else {


return false;


}


}





Number of queues


function count () {


return this.dataStore.length;


}





function dancer (name, sex) {


THIS.name = name;


This.sex = sex;


}





function getdancers (males, females) {


var names = _names.split ("\ n");


var names = _names.split ("* *");


for (var i = 0; i < names.length; ++i) {


Names[i] = Names[i].trim ();


}





for (var i = 0; i < names.length; ++i) {


var dancer = Names[i].split ("");


var sex = dancer[0];


var name = dancer[1];


if (sex = = "female") {


Females.enqueue (New dancer (name, sex));


} else {


Males.enqueue (New dancer (name, sex))


}


}


}








function dance (males, females) {


Console.log ("This group of Partners is:")


while (!females.empty () &&!males.empty ()) {


person = Females.dequeue ();


Console.log ("Female dancer is" + person.name);





person = Males.dequeue ();


Console.log ("Male dancer is" + person.name);


}


}





Test program





var _names = "female Xiao Li * * Male fu to * * men * * * Male Strong son * * * men * * * * male * * * Female MEI * * * * * female men to FU * * * * MALE * * * * * men and male xu * * Male lik *





var names = _names.split ("* *");








Test program


var maledancer = new Queue ();


var femaledancer = new Queue ();





Getdancers (Maledancer, femaledancer);


Dance (Maledancer, Femaledancer)





if (!femaledancer.empty ()) {


Console.log (Femaledancer.front (). Name + "Waiting to Dance")


}





if (!maledancer.empty ()) {


Console.log (Maledancer.front (). Name + "Waiting to Dance")


}





Show the number of people waiting to dance





var nandancers = new Queue ();


var nvdancers = new Queue ();


Getdancers (Nandancers, Nvdancers)


Dance (nandancers,nvdancers);


if (Nandancers.count () > 0) {


Console.log ("There" + nandancers.count () + "Male Dancer Waits")


}





if (Nvdancers.count () > 0) {


Console.log ("There" + mvdancers.count () + "female Dancer Waits")


}














Four: Use the queue to sort the data





Queues are used not only to perform the actions that are related to queues in a life, but also to sort data. When the computer just appears, the program is entered into the host through a punch card, each card contains a program statement. These punch cards are packed in a box and sorted by a continuation device. We can use a set of queues to simulate this process. This technique is called cardinality sorting. It's not the fastest sort algorithm, but it shows some interesting ways to use queues.





For 0-99 digits, the cardinality sort scans the data two times. The first time to sort by the number on the single digit, the second time according to 10 digits on the sorting. Each number is divided into different boxes depending on the value on the bit. The following numbers are assumed:





91,46,85,15,92,35,31,22





After the first scan in Cardinal order, the number is assigned to the following box








Bin 0:


Bin 1:91, 31


Bin 2:82, 22


Bin 3:


Bin 4:


Bin 5:85, 35


Bin 6:46


Bin 7:


Bin 8:


Bin 9:











According to the order of the boxes, the results of the first order of numbers are as follows





91,31,92,22,85,15,25,46





According to the numbers on the ten, sort again.








Bin 0:


Bin 1:15


Bin 2:22


Bin 3:31, 35


Bin 4:46


Bin 5:


Bin 6:


Bin 7:


Bin 8:85


Bin 9:91, 92











Finally, the number in the box is removed to form a new list, which is the sorted number:





15, 22, 31, 35, 46, 85, 91, 92





You can implement this algorithm by using the queue to represent the box. We need 9 queues, each corresponding to a number. All queues are stored in an array, using the rest and division operations to determine the single-digit and 10 digits. The remainder of the algorithm adds numbers to the queue, sorts them according to Single-digit values, and sorts them according to the numbers on the ten. The result is a sorted number





The following is a function that assigns numbers to the corresponding queue based on the numeric value on the corresponding bit (single-digit or 10-bit):








function Distribute (nums, queues, n, digit) {//digit represents values on Single-digit and 10 digits


for (var i = 0; i < n; ++i) {


if (digit = = 1) {


Queues[nums[i]%10].enqueue (Nums[i]);


} else {


Queues[math.floor (NUMS[I]/10). Enqueue (Nums[i])]


}


}


}











The following is a function that collects numbers from a queue








function collect (queues, nums) {


var i = 0;


for (var digit = 0; digit < ++digit) {


while (!queues[digit].empty ()) {


nums[i++] = Queues[digit].dequeue ()


}


}


}











Attach test code








function Queue () {


This.datastore = [];


This.enqueue = Enqueue;


This.dequeue = dequeue;


This.front = Front;


This.back = back;


this.tostring = toString;


This.empty = empty;


This.count = count;


}





Add an element to the end of the team


function Enqueue (Element) {


This.dataStore.push (Element)


}





Delete the elements of a team head


function Dequeue () {


return This.dataStore.shift ();


}





function Front () {//Read the elements of the team head and the end of the team


return this.datastore[0];


}


function back () {////reads the elements of the team head and the end of the team


return This.datastore[this.datastore.length-1]


}





Show all elements within a queue


function toString () {


var retstr = "";


for (var i = 0; i < this.dataStore.length; ++i) {


Retstr + = This.datastore[i] + "\ n";


}


Return RETSTR


}





Whether the queue is empty


function empty () {


if (This.dataStore.length = = 0) {


return true;


} else {


return false;


}


}





Number of queues


function count () {


return this.dataStore.length;


}





Base Sort Program


function Distribute (nums, queues, n, digit) {//digit represents values on Single-digit and 10 digits


for (var i = 0; i < n; ++i) {


if (digit = = 1) {


Queues[nums[i]%10].enqueue (Nums[i]);


} else {


Queues[math.floor (Nums[i]/a)].enqueue (Nums[i])


}


}


}





function collect (queues, nums) {


var i = 0;


for (var digit = 0; digit < ++digit) {


while (!queues[digit].empty ()) {


nums[i++] = Queues[digit].dequeue ()


}


}


}





function Disparray (arr) {


for (var i = 0; i < arr.length; ++i) {


Console.log (Arr[i] + "")


}


}





Main program





var queues = []


for (var i = 0; i < ++i) {


Queues[i] = new Queue ();


}


var nums = []


for (var i = 0; i < ++i) {


Nums[i] = Math.floor (Math.floor (Math.random () * 101))


}





Console.log ("Previous cardinality:")


Disparray (Nums);


Distribute (Nums, queues, 10, 1);


Collect (queues, nums);


Distribute (Nums,queues, 10, 10);


Collect (queues, nums);


Console.log ("Base after:")


Disparray (Nums)


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.