Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement a Stack and a Queue in JavaScript?

What is the best way to implement a Stack and a Queue in JavaScript?

I'm looking to do the shunting-yard algorithm and I'm going to need these data-structures.

like image 258
KingNestor Avatar asked Oct 19 '09 18:10

KingNestor


2 Answers

Javascript has push and pop methods, which operate on ordinary Javascript array objects.

For queues, look here:

http://safalra.com/web-design/javascript/queues/

Queues can be implemented in JavaScript using either the push and shift methods or unshift and pop methods of the array object. Although this is a simple way to implement queues, it is very inefficient for large queues — because of the methods operate on arrays, the shift and unshift methods move every element in the array each time they are called.

Queue.js is a simple and efficient queue implementation for JavaScript whose dequeue function runs in amortized constant time. As a result, for larger queues, it can be significantly faster than using arrays.

like image 24
Robert Harvey Avatar answered Oct 03 '22 05:10

Robert Harvey


var stack = []; stack.push(2);       // stack is now [2] stack.push(5);       // stack is now [2, 5] var i = stack.pop(); // stack is now [2] alert(i);            // displays 5  var queue = []; queue.push(2);         // queue is now [2] queue.push(5);         // queue is now [2, 5] var i = queue.shift(); // queue is now [5] alert(i);              // displays 2 

taken from "9 JavaScript Tips You May Not Know"

like image 51
Corey Ballou Avatar answered Oct 03 '22 04:10

Corey Ballou