javascript中的雙向隊(duì)列
1.概念
我們知道隊(duì)列是一種先進(jìn)先出的結(jié)構(gòu),只能在隊(duì)伍的開頭添加元素,隊(duì)伍的結(jié)尾刪除元素。雙向隊(duì)列的概念就是同時允許在隊(duì)伍的開頭和結(jié)尾添加和刪除元素。在javascript中有一個處理數(shù)組的方法Array.splice(index, length, array)方法,這個方法先從數(shù)組中刪除幾個元素,再加上幾個元素。這個方法的第一個參數(shù)是要從那里開始刪除元素,第二個參數(shù)標(biāo)識要刪除多少個元素,第三個參數(shù)是要從index后面要添加進(jìn)來的數(shù)組。使用splice方法可以很方便的實(shí)現(xiàn)在數(shù)組的任何位置添加,刪除元素。在隊(duì)伍開頭添加元素就是從第0個元素開始刪除0個元素,然后添加新的數(shù)組元素進(jìn)去就好了,這是不是很簡單呢。
下面我們看看雙向隊(duì)列的代碼實(shí)現(xiàn):
/*--------------雙向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; } //尾部入隊(duì),就是在數(shù)組的末尾添加一個元素 function enqueueBack(element){ this.dataStore.push(element); } //頭部入隊(duì),就是在數(shù)組的頭部添加一個元素 function enqueueFront(element){ this.dataStore.splice(0,0,element); } //尾部出隊(duì),就是刪除數(shù)組的最后一個元素 function dequeueBack(){ return this.dataStore.splice(this.dataStore.length-1, 1); } //出隊(duì),就是刪除數(shù)組的第一個元素 function dequeueFront(){ return this.dataStore.shift(); } //取出數(shù)組的第一個元素 function front(){ return this.dataStore[0]; } //取出數(shù)組的最后一個元素 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] + " " } return retStr; } //判斷數(shù)組是否為空 function empty(){ if(this.dataStore.length == 0){ return true; }else{ return false; } } //返回數(shù)組中元素的個數(shù) 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>');
輸出結(jié)果

2.判斷回文
雙向隊(duì)列可以從隊(duì)伍的開頭刪除和添加元素,用這個特性來反轉(zhuǎn)字符串是方便的,入隊(duì)之后只要依次從對頭獲取元素就可以獲取一個反轉(zhuǎn)的字符串。這樣的話我們可以很簡單判斷一個字符串是否是回文字符串,下面的代碼就是使用雙向隊(duì)列判斷字符串是否是回文。
/*---------------------------判斷字符串是否是回文-------------------------*/ 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");
輸出結(jié)果:

作者:Tyler Ning
出處:http://www.rzrgm.cn/tylerdonet/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,如有問題,請微信聯(lián)系冬天里的一把火
浙公網(wǎng)安備 33010602011771號