1 Star 0 Fork 0

Xiaoke/Data-structure-and-algorithm-code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Queue.js 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
Xiaoke 提交于 2022-07-15 16:25 . 初始化仓库
/**
* 队列
* 特点:先进先出 FIFO (类似,排队)
*
* enqueue(element(s)):向队尾添加一个或多个新的项
* dequeue:移除队列的第一项,并返回该项
* peek:返回队列中第一个元素
* isEmpty:判断是否为空
* size:返回栈里元素的长度
* clear:清空栈里的元素
* toString:数组中的toString方法
*
* @class Queue
*/
class Queue{
constructor(){
this._count = 0;
this._lowestCount = 0;
this._items = {};
}
isEmpty(){
return this._count - this._lowestCount === 0;
}
enqueue(...elem){
for(let i = 0; i < elem.length; i++){
this._items[this._count] = elem[i];
this._count ++;
}
}
dequeue(){
if(this.isEmpty()){
return undefined;
}
const result = this._items[this._lowestCount];
delete this._items[this._lowestCount];
this._lowestCount ++;
return result;
}
peek(){
if(this.isEmpty()){
return undefined;
}
return this._items[this._lowestCount];
}
size(){
return this._count - this._lowestCount;
}
clear(){
this._items = {};
this._count = 0;
this._lowestCount = 0;
}
toString(){
if(this.isEmpty()){
return '';
}
let objString = `${this._items[this._lowestCount]}`;
for(let i = this._lowestCount + 1; i < this._count; i++ )
objString = `${objString},${this._items[i]}`;
return objString;
}
}
// 测试
const queue = new Queue();
console.log(queue.isEmpty()); // true
queue.enqueue('Joho');
queue.enqueue('Jack');
console.log(queue.toString()); // Joho,Jack
queue.enqueue('Camila');
console.log(queue.size()); // 3
console.log(queue.toString()); // Joho,Jack,Camila
console.log(queue.isEmpty()); // false
queue.dequeue();
queue.dequeue();
console.log(queue.toString()); // Camila
queue.enqueue('Joho','Joho','Camila');
console.log(queue.toString());
console.log(queue);
// 击鼓传花
const hotPotato = (elementList, num) => {
const queue = new Queue();
const elimitatedList = [];
for(let i = 0; i < elementList.length; i++){
queue.enqueue(elementList[i]);
}
while(queue.size() > 1){
for(let i = 0; i < num; i++){
queue.enqueue(queue.dequeue());
}
elimitatedList.push(queue.dequeue());
}
return {
elimitated: elimitatedList,
winner: queue.dequeue()
}
}
const names = ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'];
const result = hotPotato(names, 6);
result.elimitated.forEach(name => {
console.log(`${name} 在击鼓传花中被淘汰啦`)
})
console.log(`胜利者:${result.winner}`)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/xiaaoke/Data-structure-and-algorithm-code.git
git@gitee.com:xiaaoke/Data-structure-and-algorithm-code.git
xiaaoke
Data-structure-and-algorithm-code
Data-structure-and-algorithm-code
master

搜索帮助