代码
<script>
function Queue() {
this.dataStore = [];
}
Queue.prototype.enqueue = function (data) {
this.dataStore.push(data)
}
Queue.prototype.dequeue = function () {
if (!this.empty()) {
return this.dataStore.shift();
} else {
console.log('队列为空,无法出队');
}
}
Queue.prototype.front = function () {
if (!this.empty()) {
return this.dataStore[0];
} else {
console.log('队列为空');
}
}
Queue.prototype.back = function () {
if (!this.empty()) {
return this.dataStore[this.dataStore.length - 1];
} else {
console.log('队列为空');
}
}
Queue.prototype.toString = function () {
let str = '';
for (let i = 0; i < this.dataStore.length; i++) {
str += this.dataStore[i] + ' ';
}
return str;
}
Queue.prototype.empty = function () {
if (this.dataStore.length == 0) {
return true;
} else {
return false;
}
}
</script>
测试
<script>
let queue = new Queue();
for (let i = 0; i < 5; i++) {
queue.enqueue(i);
}
console.log(queue.toString());
for (let i = 0; i < 5; i++) {
console.log('队列头为');
console.log(queue.front());
console.log('队列尾为:');
console.log(queue.back());
queue.dequeue(i);
}
queue.dequeue();
queue.front();
queue.back();
</script>