/*
基于线性表的 - 队列
尾部插入和头部删除
先进先出
*/
class ListQueue{
constructor() {
this.arr = new Array();
this.length = 0;
this.size = 10;
this.realloc = () => {
let new_arr;
if(this.length === this.size) {
// 满了 增加内存
this.size = this.size*2;
new_arr = new Array(this.size);
} else if(this.size > 10 && this.length <= Math.floor(this.size /4)) {
this.size = Math.floor(this.size /2);
new_arr = new Array(this.size);
}
if(new_arr) {
this.arr.forEach((v, i) => {
new_arr[i] = v;
});
this.arr = [...new_arr];
}
}
}
// 入队
enqueue(value){
this.arr[this.length] = value;
this.length++;
this.realloc();
}
// 出队
dequeue() {
if(!this.length) return undefined;
const value = this.arr[0];
for(let i = 0; i < (this.arr.length -1); i++){
this.arr[i] = this.arr[i+1];
}
this.length--;
this.realloc();
return value;
}
}
const list = new ListQueue();
list.enqueue(1);
list.enqueue(2);
list.enqueue(3);
list.enqueue(4);
list.enqueue(5);
console.log(list.dequeue());
console.log(list);