JavaScript Learning Summary (21)--using JavaScript arrays to implement queues and stacks in data structures

Source: Internet
Author: User

Today in the project to use JavaScript to implement the data structure of the queue and stack, here to summarize.

I. A brief introduction to queues and Stacks 1.1. Basic concepts of queues

  Queue: is a set that supports FIFO (first-in-first-out), that is, the data that is inserted before it is first taken out!

  As shown in the following:

  

1.2, the basic concept of the stack

  Stack: A collection that supports last-in, first-out (LIFO), which is the data that is inserted after it is first taken out!

  As shown in the following:

  

Ii. implementing queues and stacks in JavaScript

Implementing queues and Arrays in JavaScript is primarily through arrays, and the following methods are available in the JS array to make it easy to implement queues and stacks:

    • Shift: Removes the first element from the array and returns the value of the element.
    • Unshift: Adds one or more elements to the beginning of the array and returns the new length
    • Push: Adds an element at the end of the array and returns the new length
    • Pop: Removes the last element from the array and returns the value of the element.
2.1. Implement the queue
1 <script type= "Text/javascript" >2//Create an array to simulate the queue3var a=NewArray ();4Console.log (a);5//Unshift: Adds one or more elements to the beginning of the array and returns the new length6 Console.log ("queue"));7 A.unshift (1)8 Console.log (a);//----->19 A.unshift (2);Ten Console.log (a);//----->2,1A.unshift (3);Console.log (a);//----->3,2,1A.unshift (4);Console.log (a);//----->4,3,2,1Console.log ("Team out, FIFO");16Console.log (a);17//Pop: Removes the last element from the array and returns the value of the elementA.pop (); //----->1 Console.log (a);  A.pop (); //----->2 Console.log (a);  A.pop (); //----->3 Console.log (a);  A.pop (); //----->4 Console.log (a);  </script>                

The effect in the Google Chrome console output is as follows:

  

2.2. Implementing stacks
1 <script type= "Text/javascript" >2//Create an array to emulate the stack3var a=NewArray ();4Console.log (a);5//Push: Adds one or more elements to the end of the array and returns the new length6 Console.log ("into the stack");7 A.push (1)8 Console.log (a);//----->19 A.push (2);Ten Console.log (a);//----->1,2A.push (3);Console.log (a);//----->1,2,3A.push (4);Console.log (a);//----->1,2,3,4Console.log ("Out of Stack, LIFO");16Console.log (a);17//Pop: Removes the last element from the array and returns the value of the elementA.pop (); //----->4 Console.log (a);  A.pop (); //----->3 Console.log (a);  A.pop (); //----->2 Console.log (a);  A.pop (); //----->1 Console.log (a);  </script>                

The effect in the Google Chrome console output is as follows:

  

2.3. Performance test of Push method and Unshift method

Both the push and unshift methods of the array can add elements to the current array, but the push is added at the end, and Unshift is added at the beginning, so the principle is that the unshift is less efficient. The reason is that every element it adds, it moves the existing element down one position. But how effective is the difference? Here's a quick test.

1 <script type= "Text/javascript" >2/*3About the code "var s=+newdate ();" Tips on how To4The explanation is as follows: =+ This operator does not exist;5+ equivalent to. valueOf ();6+new Date () is the equivalent of new date (). ValueOf ()74 results returns the number of milliseconds for the current time8Alert (+new Date ());9Alert (+new Date);10var s=new Date ();11Alert (s.valueof ());12Alert (S.gettime ());13*/14var arr =[ ];15var startTime = +New Date ();//+new date () is equivalent to new Date (). ValueOf (), the number of milliseconds to return the current time16//Push performance Test17for (var i = 0; I < 100000; i++) {18Arr.push (i);19}20var endTime = +NewDate ();Console.log ("Call the Push method to add 100,000 elements to the array time consuming" + (Endtime-starttime) + "milliseconds");22StartTime = +new Date (); 24 arr = []; 25 // unshift performance Test 26 for (var i = 0; i < 100000; i++< Span style= "color: #000000") {27  Arr.unshift (i); 28 }29 endTime = +new Date ();  Console.log ("Call the Unshift method to add 100,000 elements to the array time" + (Endtime-starttime) + "milliseconds" 31 </script>           

This code performs 100,000 push and unshift operations, running in Google Chrome once, and the results are as follows:
  
As you can see, unshift is almost 100 times times slower than push! Therefore, usually should be cautious to use unshift, especially for large arrays. If you must achieve the unshift effect, you can use the reverse method of the array, the reverse method of array can reverse an array. First, the element to be put into the array is added with push, and then once reverse is executed, the unshift effect is achieved. Like what:

1 <script type= "Text/javascript" >2//Create an array to emulate the stack3var a=NewArray ();4//To add an element to the end of an array using the Push method5 A.push (1)6 A.push (2);7 A.push (3); 8 A.push (4); 9 Console.log ("sequence of elements in an array before the inverse of the array");  Ten Console.log (a); //----->1,2,3,4 //Array There is a method called reverse that can invert an array. First put the elements to be put into the array with push to add, and then perform a reverse, to achieve the effect of Unshift a.reverse ();  use the reverse method to invert the array console.log ("sequence of elements in an array after an array reversal");  Console.log (a);  </script>                

The effect in the Google Chrome console output is as follows:

  

From the running result, the order of the array elements has been reversed.

2.4. Performance test of Reverse method

The performance of reverse, and then to test:

1 <script type= "Text/javascript" >2 var arr = [], s = +new Date; 3 for (var i = 0; i < 100000 ; I++) {4  Arr.push (i); 5 }6 // Call the reverse method to invert the order of the 100000 elements inside the array  7  Arr.reverse (); 8 console.log ("Calling the reverse method reverses the order of the 100000 elements inside the array time consuming:" + (+ New Date-s) + "MS" 9 </script>            

The effect in the Google Chrome console output is as follows:

  
It can be seen from the running effect that the reverse method has high performance and can be used with confidence.

The above is a summary of the queues and stacks implemented in JavaScript using arrays, and simply tests the performance of Push, unshift, and reverse in manipulating large arrays.

JavaScript Learning Summary (21)--using JavaScript arrays to implement queues and stacks in data structures

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.