欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS棧stack類的實現(xiàn)與使用方法示例

 更新時間:2019年01月31日 11:52:16   作者:白楊-M  
這篇文章主要介紹了JS棧stack類的實現(xiàn)與使用方法,結合實例形式分析了棧的原理,以及javascript定義與使用棧的基本操作技巧,需要的朋友可以參考下

本文實例講述了JS棧stack類的實現(xiàn)與使用方法。分享給大家供大家參考,具體如下:

棧是一種“先進后出”的數(shù)據(jù)結構,原理如下圖所示:

示例代碼:

/*使用棧stack類的實現(xiàn)*/
function stack() {
  this.dataStore = [];//保存棧內(nèi)元素,初始化為一個空數(shù)組
  this.top = 0;//棧頂位置,初始化為0
  this.push = push;//入棧
  this.pop = pop;//出棧
  this.peek = peek;//查看棧頂元素
  this.clear = clear;//清空棧
  this.length = length;//棧內(nèi)存放元素的個數(shù)
}
function push(element){
  this.dataStore[this.top++] = element;
}
function pop(){
  return this.dataStore[--this.top];
}
function peek(){
  return this.dataStore[this.top-1];
}
function clear(){
  this.top = 0;
}
function length(){
  return this.top;
}
/*測試stack類的實現(xiàn)*/
var s = new stack();
s.push("aa");
s.push("bb");
s.push("cc");
console.log(s.length());//3
console.log(s.peek());//cc
var popped = s.pop();
console.log(popped);//cc
console.log(s.peek());//bb

這里使用在線HTML/CSS/JavaScript代碼運行工具http://tools.jb51.net/code/HtmlJsRun測試上述代碼,可得如下運行結果:

希望本文所述對大家JavaScript程序設計有所幫助。

相關文章

最新評論