//一般队列 class queue { constructor() { this.list = []; } //入队 EnQueue(item) { this.list.push(item); } //出队 Dequeue() { return this.list.shift(); } //第一个元素值 GetFront() { return this.list[0]; } //长度 GetSize() { return this.list.length; } //是否为空 GetIsEmpty() { return this.list.length == 0; } // 清空 Clear() { this.list = []; } //读取元素 Read() { console.log(this.list.toString()); } } let queueTest = new queue(); queueTest.GetIsEmpty();//true queueTest.EnQueue(1); queueTest.EnQueue(2); queueTest.EnQueue(3); queueTest.Read();//1,2,3 queueTest.Dequeue();//1 queueTest.Read();//2,3 //优先队列:1:老年人和孕妇(或 带小孩的妇女)登机时也享有高于其他乘客的优先级; //医生会优先处理病情比较严重的患者 class PriorityQueue { constructor() { this.list = []; } //入队 EnQueue(item, priority) { var f = { item: item, index: priority }; if (this.list.length == 0) this.list.push(f); else { var position = this.list.findIndex(x => x.index > f.index); if (position == -1) this.list.push(f); else this.list.splice(position, 0, f); } } //出队 Dequeue() { return this.list.shift(); } //第一个元素值 GetFront() { return this.list[0]; } //长度 GetSize() { return this.list.length; } //是否为空 GetIsEmpty() { return this.list.length == 0; } // 清空 Clear() { this.list = []; } //读取元素 Read() { console.log(this.list); } } var priorityQueue = new PriorityQueue(); priorityQueue.GetIsEmpty();//true; priorityQueue.EnQueue(1, 1); priorityQueue.EnQueue(2, 2); priorityQueue.EnQueue(22, 3); priorityQueue.EnQueue(22, 5); priorityQueue.Read();//[{item:1,index:1},{item:2,index:2},{item:22,index:3},{item:22,index:5}] priorityQueue.EnQueue(33, 4); priorityQueue.Read();//[{item:1,index:1},{item:2,index:2},{item:22,index:3},{item:22,index:4},{item:22,index:5}] priorityQueue.Dequeue();//{item:1,index:1} //循环队列 //为充分利用向量空间,克服"假溢出"现象的方法是:将向量空间想象为一个首尾相接的圆环,并称这种向量为循环向量。 class LoopQueue extends queue { constructor(items) { super(items) } getIndex(index) { const length = this.list.length return index > length ? (index % length) : index } find(index) { return !this.isEmpty ? this.list[this.getIndex(index)] : null } } var loopQueue=new LoopQueue(); loopQueue.EnQueue(1); loopQueue.EnQueue(2); loopQueue.EnQueue(3); loopQueue.Read();//1,2,3 loopQueue.find(7);//2