本文實(shí)例講述了javascript編程實(shí)現(xiàn)棧的方法。分享給大家供大家參考,具體如下:
棧是限定僅在表尾進(jìn)行插入或刪除操作的線性表,棧是先進(jìn)后出的。棧的表尾稱為棧頂(top),而表頭端稱為棧底(bottom)。
和線性表類似,棧也有兩種存儲(chǔ)表示方法,順序棧和鏈棧。
這里講一下順序棧,設(shè)置指針top指示棧頂元素在順序棧中的位置。通常的做法就是以top=0表示空棧。base為棧底指針,top為棧頂指針。
如果base為null,則表示棧結(jié)構(gòu)不存在,如果top=base則表示空棧。每當(dāng)插入一個(gè)新的元素,top+1,刪除元素,top-1。因此,非空棧中top始終在棧頂元素的下一位置上。
如下圖所示

JavaScript中自帶了數(shù)組的push和pop方法,其原理無非就是數(shù)組最后繼續(xù)添加和刪除數(shù)組最后一個(gè)元素。這里我們自己實(shí)現(xiàn)一遍棧的操作,代碼如下:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>JS棧</title> </head> <body> <script type="text/javascript"> function Stack(count){ var top=-1;//top頭指針 this.myArray=new Array(); if(count!=undefined){ this.count=count; this.myArray=new Array(this.count); }else{ this.count=0; } //入棧 this.In=function(value){ if(top==this.count){ return false; }else{ ++top; this.myArray[top]=value; return true; } return false; } //出棧 this.Out=function(){ if(top==-1){ return false; }else{ var removeValue=this.myArray[top]; this.myArray[top]=null; top--; return removeValue; } } this.Clear=function(){ this.top=-1; } //遍歷棧 this.tostring=function(){ for(var i=0;i<this.myArray.length;i++){ document.write(this.myArray[i]+'<br>'); } } } Stack(3); In(1); In(2); In(3); tostring();//1 2 3 Out(); Out(); tostring();//1 null null In(4); tostring();//1 4 null </script> </body></html>首先需要定義頭指針
function Stack(count){ var top=-1;//top頭指針 this.myArray=new Array(); if(count!=undefined){ this.count=count; this.myArray=new Array(this.count); }else{ this.count=0; }然后是入棧操作
//入棧this.In=function(value){ if(top==this.count){ return false; }else{ ++top; this.myArray[top]=value; return true; } return false;}和出棧操作
//出棧this.Out=function(){ if(top==-1){ return false; }else{ var removeValue=this.myArray[top]; this.myArray[top]=null; top--; return removeValue; }}鏈棧的操作和鏈表類似,這里就不做詳細(xì)介紹了。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》、《JavaScript排序算法總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》及《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注