views:

356

answers:

5

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.

+14  A: 
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"

cballou
I would advise caution in using queue.shift. IIRC it is not O(1), but O(n) and might be too slow if the queue gets large.
MAK
I'd say this depends on the javascript implementation. I don't think it's defined in the javascript spec.
Georg
@MAK/gs: queues are dense, so most JS implementations should store the values in an actual, dynamically-sized array (what Java calls `ArrayList`); this means shifting will most likely involve a `memmove()`; you'd have to check the sources of your JS engine of choice to make sure, though...
Christoph
+2  A: 

Arrays.

Stack:

var stack = [];

//put value on top of stack
stack.push(1);

//remove value from top of stack
var value = stack.pop();

Queue:

var queue = [];

//put value on end of queue
queue.push(1);

//Take first value from queue
var value = queue.shift();
Jani Hartikainen
A: 

The regular Array structure in Javascript is a Stack (first in, last out) and can also be used as a Queue (first in, first out) depending on the calls you make.

Check this link to see how to make an Array act like a Queue:

Queues

Justin Niessner
+2  A: 

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 the methods operate on arrays, the shift and unshift methods move every element in the array each time they are called.

Robert Harvey
+1 for link to implementation of a delayed shift queue
Christoph
A: 

Create a pair of classes that provide the various methods that each of these data structures has (push, pop, peek, etc). Now implement the methods. If you're familiar with the concepts behind stack/queue, this should be pretty straightforward. You can implement the stack with an array, and a queue with a linked list, although there are certainly other ways to go about it. Javascript will make this easy, because it is weakly typed, so you don't even have to worry about generic types, which you'd have to do if you were implementing it in Java or C#.

echo