上一篇数据结构讲到了栈,队列和栈很是相似。队列也是一种特殊的列表,它与栈的区别在于,栈是先入后出,而队列则是遵循FIFO先入先出的原则,换言之队列只能在队尾插入元素,而在队列的头部去删除元素。数据结构
举个简单的例子,队列就至关于在生活中排队购物,后来的人须要排在队尾,而队伍最前面的人会一次结帐后出列。队列的应用很是普遍,经常使用于实现缓冲区,广度优先搜索,优先级队列等等。ui
队列最主要的两个操做分别是enqueue(入列)和dequeue(出列)this
经过上面这张图咱们能够看到队列的几个特色spa
初始化指针
class Queue { constructor(max=1000){ // 定义一块连续的存储空间用来存储数据 this.data = new Array(1000); // 开辟的空间大小 this.max = max; // 头部位置 this.head = 0; // 尾部位置 this.tail = 0; // 数据长度 this.size = 0; } }
enqueue 入列code
enqueue(x) { // 溢出 if(this.size === this.max){ throw 'overflow' } // 添加新数据到尾部 this.data[this.tail] = x; // 数据长度+1 this.size++; // 尾部指针向后挪动一位,若是后面没有空间,则指向0 if(this.tail === this.max-1){ this.tail = 0; }else{ this.tail++ } }
dequeue出列blog
dequeue(){ if(this.size === 0){ throw 'underflow'; } const x = this.data[this.head]; this.head++; this.size--; return x; }
class Queue { constructor(max = 1000) { this.data = new Array(max); this.max = max; this.head = 0; this.tail = 0; this.size = 0; } // 入列 enqueue(x) { if (this.size === this.max) { throw 'overflow'; } this.data[this.tail] = x; this.size++; if (this.tail === this.max - 1) { this.tail = 0; } else { this.tail++; } } // 出列 dequeue() { if (this.size === 0) { throw 'underflow'; } const x = this.data[this.head]; this.head++; this.size--; return x; } get length() { return this.size; } } module.exports = Queue;
队列也能够经过两个栈来实现,不了解栈的同窗能够看上一篇关于栈文章,接下来会引入以前写好的栈,具体代码见下面。队列
// 上一节中,栈的实现代码 const Stack = require('./stack'); class Queue { constructor(max=1000){ // 实例化两个栈,分别是s1和s2, s1栈用来作入列,s2栈用来出列使用 this.s1 = new Stack(max); this.s2 = new Stack(max); this.max = max; } // 入列 enqueue(x) { if(this.s1.length === this.max){ throw 'overflow' } // s1做为入列 this.s1.push(x); } // 出列 dequeue(){ if(this.s2.length>0){ return this.s2.pop; } while(this.s1.length){ this.s2.push(this.s1.pop()); } return this.s2.pop(); } }
在这里大体简单的说明一下以上用两个栈来实现队列的逻辑吧。图片
下一张的数据结构会为你们介绍链表get