2017-10-13 01:12:48 +08:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
module.exports = class Queue {
|
|
|
|
constructor(items) {
|
|
|
|
this.first = null;
|
|
|
|
this.last = null;
|
2017-12-01 16:48:24 +08:00
|
|
|
this.recycle = [];
|
2017-10-13 01:12:48 +08:00
|
|
|
this.length = 0;
|
|
|
|
if(items) {
|
|
|
|
for(const item of items) {
|
|
|
|
this.enqueue(item);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
enqueue(item) {
|
|
|
|
const first = this.first;
|
2017-12-01 16:48:24 +08:00
|
|
|
let node;
|
|
|
|
if(this.recycle.length > 0) {
|
|
|
|
node = this.recycle.pop();
|
|
|
|
node.item = item;
|
|
|
|
node.next = null;
|
|
|
|
} else {
|
|
|
|
node = {
|
|
|
|
item,
|
|
|
|
next: null
|
|
|
|
};
|
|
|
|
}
|
2017-10-13 01:12:48 +08:00
|
|
|
if(first === null) {
|
|
|
|
this.last = node;
|
|
|
|
} else {
|
|
|
|
first.next = node;
|
|
|
|
}
|
|
|
|
this.first = node;
|
|
|
|
this.length++;
|
|
|
|
}
|
|
|
|
|
|
|
|
dequeue() {
|
|
|
|
const last = this.last;
|
|
|
|
if(last === null)
|
|
|
|
return undefined;
|
|
|
|
const next = last.next;
|
|
|
|
if(next === null) {
|
|
|
|
this.first = null;
|
|
|
|
}
|
|
|
|
this.last = next;
|
|
|
|
this.length--;
|
2017-12-01 16:48:24 +08:00
|
|
|
this.recycle.push(last);
|
2017-10-13 01:12:48 +08:00
|
|
|
return last.item;
|
|
|
|
}
|
|
|
|
};
|