javascript中的双向队列

时间:2023-03-08 18:55:05
javascript中的双向队列

1.概念

  我们知道队列是一种先进先出的结构,只能在队伍的开头添加元素,队伍的结尾删除元素。双向队列的概念就是同时允许在队伍的开头和结尾添加和删除元素。在javascript中有一个处理数组的方法Array.splice(index, length, array)方法,这个方法先从数组中删除几个元素,再加上几个元素。这个方法的第一个参数是要从那里开始删除元素,第二个参数标识要删除多少个元素,第三个参数是要从index后面要添加进来的数组。使用splice方法可以很方便的实现在数组的任何位置添加,删除元素。在队伍开头添加元素就是从第0个元素开始删除0个元素,然后添加新的数组元素进去就好了,这是不是很简单呢。

  下面我们看看双向队列的代码实现:

/*--------------双向Queue类的定义和测试代码----------------*/
function Queue(){
this.dataStore = [];
this.enqueueFront = enqueueFront;
this.enqueueBack = enqueueBack;
this.dequeueFront = dequeueFront;
this.dequeueBack = dequeueBack;
this.front = front;
this.back = back;
this.toString = toString;
this.empty = empty;
} //尾部入队,就是在数组的末尾添加一个元素
function enqueueBack(element){
this.dataStore.push(element);
} //头部入队,就是在数组的头部添加一个元素
function enqueueFront(element){
this.dataStore.splice(0,0,element);
} //尾部出队,就是删除数组的最后一个元素
function dequeueBack(){
return this.dataStore.splice(this.dataStore.length-1, 1);
} //出队,就是删除数组的第一个元素
function dequeueFront(){
return this.dataStore.shift();
} //取出数组的第一个元素
function front(){
return this.dataStore[0];
}
//取出数组的最后一个元素
function back(){
return this.dataStore[this.dataStore.length-1];
} function toString(){
var retStr = "";
for (var i=0; i<this.dataStore.length; ++i) {
retStr += this.dataStore[i] + "&nbsp;"
}
return retStr;
}
//判断数组是否为空
function empty(){
if(this.dataStore.length == 0){
return true;
}else{
return false;
}
}
//返回数组中元素的个数
function count(){
return this.dataStore.length;
} var q = new Queue();
q.enqueueFront("1");
q.enqueueFront("2");
q.enqueueBack("3");
q.enqueueBack("4");
document.write(q.toString());
document.write('<br>'); q.dequeueFront();
document.write(q.toString());
document.write('<br>'); q.dequeueBack();
document.write(q.toString());
document.write('<br>');
document.write('<br>');

输出结果

javascript中的双向队列

2.判断回文

  双向队列可以从队伍的开头删除和添加元素,用这个特性来反转字符串是方便的,入队之后只要依次从对头获取元素就可以获取一个反转的字符串。这样的话我们可以很简单判断一个字符串是否是回文字符串,下面的代码就是使用双向队列判断字符串是否是回文。

/*---------------------------判断字符串是否是回文-------------------------*/
function isPalindrome(str){
var queue = new Queue();
for (var i=0; i<str.length; i++) {
queue.enqueueFront(str[i]);
} var newStr = "";
while (!queue.empty()){
newStr += queue.dequeueFront();
} document.write(newStr);
document.write('<br>');
if(str == newStr){
document.writeln(str + " 是回文");
}else{
document.writeln(str + " 不是回文");
}
} isPalindrome("racecar");
document.write('<br>');
isPalindrome("helloword");

输出结果:

javascript中的双向队列