1 Star 0 Fork 0

math.most/js_study

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
026队列封装.js 1.77 KB
一键复制 编辑 原始数据 按行查看 历史
math.most 提交于 2021-09-21 09:28 +08:00 . 补充
/**
* 示例一: 基础使用
*/
// 1. 封装队列类(基于数组形式) 先进先出
function Queue() {
this.items = []
Queue.prototype.enqueue = function (element) {
this.items.push(element)
}
Queue.prototype.dequeue = function () {
return this.items.shift()
}
Queue.prototype.front = function () {
return this.items[0]
}
Queue.prototype.isEmpty = function () {
return this.items.length == 0
}
Queue.prototype.size = function () {
return this.items.length
}
Queue.prototype.toString = function () {
var itemsToString = ''
this.items.forEach(item => {
itemsToString += item + ','
});
return itemsToString
}
}
// 2. 队列使用
var queue = new Queue()
queue.enqueue('abc')
queue.enqueue('def')
queue.enqueue('ghj')
console.log(queue) // Queue { items: [ 'abc', 'def', 'ghj' ] }
queue.dequeue()
console.log(queue) // Queue { items: [ 'def', 'ghj' ] }
console.log(queue.front()) // def
console.log(queue.isEmpty()) // false
console.log(queue.toString()) // def,ghj,
/**
* 示例二: 击鼓传花
*/
function PassGame(NameList, num) {
// NameList: 参与游戏的人员
// num: 指定游戏中被淘汰的个数
var q = new Queue()
// 1. 将所有人加入到队列中
NameList.forEach(item => {
q.enqueue(item)
})
// 2. 开始游戏
while (q.size() > 1) {
// 将被指定的人删除且将他之前的元素加入到队列中
for(i = 0; i < num - 1; i++) {
q.enqueue(q.dequeue())
}
q.dequeue()
}
return '获胜的人是:' + q.front()
}
gameNames = ['lilei', 'zhangsan', 'wangwu', 'hanmeimei', 'hanxin']
console.log(PassGame(gameNames, 3)) // 获胜的人是:hanmeimei
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/mathmost/js_study.git
git@gitee.com:mathmost/js_study.git
mathmost
js_study
js_study
master

搜索帮助