队列定义:队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作;
es5(function) 实现:
// 基于数组封装队列类
function Queue(defaultValues = []) {
// 属性
this.items = defaultValues;
// 方法
// 1.enqueue():将元素加入到队列中
Queue.prototype.enqueue = (element) => {
this.items.push(element);
};
// 2.dequeue():从队列中删除前端元素
Queue.prototype.dequeue = () => {
return this.items.shift();
};
// 3.front():查看前端的元素
Queue.prototype.front = () => {
return this.items[0];
};
// 4.isEmpty:查看队列是否为空
Queue.prototype.isEmpty = () => {
return this.items.length === 0;
};
// 5.size():查看队列中元素的个数
Queue.prototype.size = () => {
return this.items.length;
};
// 6.toString():将队列中元素以字符串形式输出
Queue.prototype.toString = () => {
let resultString = '';
for (let i of this.items) {
resultString += `${i}`;
}
return resultString;
};
// 打印
Queue.prototype.print = () => {
console.log(this.items.toString());
};
}
es6(class)实现:
// 基于数组封装队列类
class Queue {
constructor(defaultValues = []) {
// 属性
this.items = defaultValues;
}
// 方法
// 1.enqueue():将元素加入到队列中
enqueue(element) {
this.items.push(element);
}
// 2.dequeue():从队列中删除前端元素
dequeue() {
return this.items.shift();
}
// 3.front():查看前端的元素
front() {
return this.items[0];
}
// 4.isEmpty:查看队列是否为空
isEmpty() {
return this.items.length === 0;
}
// 5.size():查看队列中元素的个数
size() {
return this.items.length;
}
// 6.toString():将队列中元素以字符串形式输出
toString() {
let resultString = '';
for (let i of this.items) {
resultString += `${i}`;
}
return resultString;
}
// 打印
print() {
console.log(this.items.toString());
}
}
const myQuene = new Queue([1, 2, 3]);
myQuene.enqueue(5);
myQuene.print();