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.


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

取自“9个你可能不知道的JavaScript技巧”


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.

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


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();
链接地址: http://www.djcxy.com/p/14084.html

上一篇: 最大调用堆栈大小超过错误

下一篇: 你如何在JavaScript中实现堆栈和队列?