HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youhowandqueuestackimplementjavascript

Problem

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.

Solution

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"

Context

Stack Overflow Q#1590247, score: 1740

Revisions (0)

No revisions yet.