資料結構棧之javascript實現
阿新 • • 發佈:2018-12-23
棧是一種支援後進先出(LIFO)的集合,即後被插入的資料,先被取出,棧的示意圖如圖1。
圖1
首先宣告建構函式Stack,裡面定義我們需要的屬性和方法,程式碼如下。
function Stack(){
//用於儲存棧元素的陣列
this.dataStore = [];
//記錄dataStore中元素的個數,由於陣列的下標是從0開始的,所以相當於指向棧中頂部元素下標+1的位置,也可以理解為指向下一個入棧元素的下標位置。
this.top =0;
//入棧方法
this.push = push;
//出棧方法
this.pop = pop;
//返回頂部的棧元素
this.peek = peek;
//清除棧元素
this.clear = clear;
//返回棧元素個數
this.length = length;
}
push方法實現
棧中向top位置插入元素後,top值更新,元素個數+1。
function push (element) {
this.dataStore[this.top++] = element;
}
pop方法實現
元素出棧,top值減1,指向當前棧頂元素下標位置,刪除該元素作為出棧操作。
function pop() {
var topvalue = this.dataStore[--this.top];
delete this.dataStore[this.top];
return topvalue;
}
peek方法實現
peek方法返回頂部的棧元素,即取dataStore的最後一個位置的值,也就是dataStore下標為top-1的值,
function peek() {
return this.dataStore[this.top-1];
}
clear方法實現
clear 方法清除棧內元素,把棧的長度重置為0,另外還要把dataStore陣列置空,因為陣列中的元素始終被dataStore引用,導致垃圾回收器無法將其回收,從而造成記憶體浪費
function clear () {
this.top = 0;
//下面兩句任選其一清除陣列dataStore裡的資料
// this.dataStore = [];
this.dataStore.length = 0;
}
length 方法實現
length 方法獲取棧中的元素個數top,
function length() {
return this.top;
}
下面寫段程式碼測試一下;
var a = new Stack();
a.push(1);
a.push(2);
a.push(3);
console.log("開始的dataStore為:"+a.dataStore+" 棧的長度為:"+a.length()); //輸出:開始的dataStore為:1,2,3 棧的長度為:3
a.pop();
console.log("出棧一個值後dataStore為:"+a.dataStore+" 棧的長度為:"+a.length()); //輸出:出棧一個值後dataStore為:1,2, 棧的長度為:2
a.clear();
console.log("清除棧後dataStore為:"+a.dataStore+" 棧的長度為:"+a.length()); //輸出:清除棧後dataStore為: 棧的長度為:0