队列的定义
队列(Queue)是一种遵从先进先出(First in, first out。简称FIFO)原则的有序集合。
用组合模式实现
function Queue(){ this.items = []; } Queue.prototype={ constructor:Queue, //入队 enqueue:function() { var len = arguments.length; if (len == 0) { return; } for (var i = 0; i < len; i++) { this.items.push(arguments[i]) } }, //出队 dequeue:function() { var result = this.items.shift(); return typeof result != 'undefined' ? result : false; }, //队列是否为空 isEmpty:function() { return this.items.length == 0; }, //返回队列长度 size:function() { return this.items.length; }, //清空队列 clear:function() { this.items = []; }, //返回队列 show:function() { return this.items; } }var que1=new Queue(); que1.enqueue(1,2,3); que1.enqueue({},2,4);console.log(que1.dequeue());
用es6-class实现更优雅
class Queue{ constructor(){ this.items=[]; } //入队 enqueue() { var len = arguments.length; if (len == 0) { return; } for (var i = 0; i < len; i++) { this.items.push(arguments[i]) } } //出队 dequeue() { var result = this.items.shift(); return typeof result != 'undefined' ? result : false; } //队列是否为空 isEmpty() { return this.items.length == 0; } //返回队列长度 size() { return this.items.length; } //清空队列 clear() { this.items = []; } //返回队列 show() { return this.items; } }
栈的实现其实差不了太多
作者:pattyzzh
链接:https://www.jianshu.com/p/22b8f9d00331