由于最近写JavaScript的时候需要用到队列这一数据结构,但JavaScript没有现成的队列这一数据结构,因此我们可以通过自己构造而获得。而此处实现的队列仅供大家参考,其实现方式还可以通过其他方式实现;其调用方法同C/C++中类似,通过push入队,通过pop从队首出队。
JavaScript队列构造代码如下:
function Queue() {
var dataStore = [];
//向队末尾添加一个元素
this.push = function(element) {
dataStore.push(element)
}
//删除队首的元素
this.pop = function() {
return dataStore.shift();
}
this.front = function() { //读取队首的元素
return dataStore[0];
}
this.back = function() { 读取队末的元素
return dataStore[dataStore.length - 1]
}
//读取指定元素
this.getElement = function(index) {
if(index >= 0 && index < dataStore.length){
return dataStore[index];
}
}
//设置指定元素数据
this.setElement = function(index, element) {
dataStore[index] = element;
}
//显示队列内的所有元素
this.toString = function() {
var retStr = "";
for (var i = 0; i < dataStore.length; ++i ) {
retStr += dataStore[i] + "\n";
}
return retStr
}
//队列是否为空
this.empty = function() {
if (dataStore.length == 0) {
return true;
} else {
return false;
}
}
//队列个数
this.count = function() {
return dataStore.length;
}
}