JavaScript中的队列的实现
function Queue() {
var items = []
//enqueue 从队列尾部添加一个元素
this.enqueue = function(item) {
items.push(item)
}
//dequeue 从队列头部删除一个元素
this.dequeue = function() {
return items.shift()
}
//head 返回头部的元素
this.head = function() {
return items[0]
}
//size 返回队列大小
this.size = function() {
return items.length
}
//clear清空队列
this.clear = function() {
items = []
}
//isEmpty判断队列是否为空
this.isEmpty = function() {
return items.length === 0
}
}
相关练习题
1.约瑟夫环:有一个数组a[100]存放0-99,要求每隔两个数删掉一个数,到末尾时循环至开头继续进行,求最后一个被删掉的数。
思路分析:前10个数是0 1 2 3 4 5 6 7 8 9,所谓每隔两个数删掉一个数其实就是把2 5 8删除掉,如果只是从0到99每两个数字删掉一个数,