We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
队列(Queue),它是一种运算受限的线性表,先进先出(FIFO First In First Out)
enqueue(element)
dequeue()
front()
isEmpty()
size()
function Queue(){ var items = []; this.enqueue = function(element){ items.push(element) } this.dequeue = function(){ return items.shift() } this.front = function(){ return items[0] } this.isEmpty = function(){ return items.length == 0 } this.size = function(){ return items.length } }
function PriorityQueue(){ var items = []; var QueueElement = function(element, priority){ this.element = element; this.priority = priority; } this.enqueue = function(element, priority){ var queueElement = new QueueElement(element, priority) if(this.isEmpty()){ items.push(queueElement) }else{ var flag = false; for(var i=0;i<this.size();i++){ if(queueElement.priority<items[i].priority){ items.splice(i, 0, queueElement); flag = true; break } } if(!flag){ items.push(queueElement) } } } this.dequeue = function(){ return items.shift() } this.front = function(){ return items[0] } this.isEmpty = function(){ return items.length == 0 } this.size = function(){ return items.length } }
击鼓传花的规则 原游戏规则: 班级中玩一个游戏, 所有学生围成一圈, 从某位同学手里开始向旁边的同学传一束花. 这个时候某个人(比如班长), 在击鼓, 鼓声停下的一颗, 花落在谁手里, 谁就出来表演节目. 修改游戏规则: 我们来修改一下这个游戏规则. 几个朋友一起玩一个游戏, 围成一圈, 开始数数, 数到某个数字的人自动淘汰. 最后剩下的这个人会获得胜利, 请问最后剩下的是原来在哪一个位置上的人?
function Queue(){ var items = []; this.enqueue = function(element){ items.push(element) } this.dequeue = function(){ return items.shift() } this.front = function(){ return items[0] } this.isEmpty = function(){ return items.length == 0 } this.size = function(){ return items.length } } //实现击鼓传花的函数 function passGame(nameList, num) { var queue = new Queue(); for(var i=0;i<nameList.length;i++){ queue.enqueue(nameList[i]) } while(queue.size>1){ for(var i=1;i<num;i++){ queue.enqueue(queue.dequeue()) } queue.dequeue() } return queue.front() + " 所处位置: "+ (nameList.indexOf(queue.front())+1) } //验证结果 var names = ['John','Jack','Camila','Ingrid','Carl']; var index = passGame(names, 8) // 数到8的人淘汰 console.log( index)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
队列结构
队列(Queue),它是一种运算受限的线性表,先进先出(FIFO First In First Out)
代码实现
操作方法
enqueue(element)
:向队列尾部添加一个(或多个)新的项。dequeue()
:移除队列的第一(即排在队列最前面的)项,并返回被移除的元素。front()
:返回队列中第一个元素——最先被添加,也将是最先被移除的元素。队列不做任何变动(不移除元素,只返回元素信息——与Stack类的peek方法非常类似)。isEmpty()
:如果队列中不包含任何元素,返回true,否则返回false。size()
:返回队列包含的元素个数,与数组的length属性类似。代码实现
优先级队列
代码实现
应用
参考链接
The text was updated successfully, but these errors were encountered: