GitHub: https://github.com/BadWaka/data-structure-algorithm/blob/master/stack/stack.html
// 棧
var Stack = function (size) {
this.stack = new Array(size); // 新建內存空間
this.size = size; // 棧容量
this.top = 0; // 棧頂
var that = this;
// 判斷棧是否為空
this.isStackEmpty = function () {
return that.top === 0;
};
// 判斷棧是否為滿
this.isStackFull = function () {
return that.top === that.size;
};
// 清空一個棧
this.clearStack = function () {
that.top = 0;
// that.stack.splice(0, that.stack.length); // 不是必要的,因為即使棧里有值也沒有關系,只要棧頂為0了,之前的值就再也取不到了
};
// 獲得棧的元素個數
this.getStackLength = function () {
return that.top; // 棧頂的值即可以表示棧元素的多少
};
// 入棧
this.push = function (element) {
if (that.isStackFull()) {
console.log('棧已滿,入棧失敗 element = ' + element);
return false;
}
that.stack[that.top] = element;
that.top++;
return true;
};
// 出棧
this.pop = function () {
if (that.isStackEmpty()) {
console.log('空棧,出棧失敗');
return false;
}
// 這里要注意,棧頂指向的是一個空的地方,用來放元素的;所以取得時候先top--,再取值
that.top--;
var element = that.stack[that.top];
console.log('出棧成功 element = ' + element);
return element;
};
/**
* 遍歷棧
*
* @param isFromTop 是否從棧頂開始
* @param handler 處理函數
*/
this.traverseStack = function (isFromTop, handler) {
var stackStr = '';
var i;
if (isFromTop) {
for (i = that.top - 1; i >= 0; i--) {
stackStr += that.stack[i] + ' ';
if (handler) {
handler(that.stack[i]);
}
}
} else {
for (i = 0; i < that.top; i++) {
stackStr += that.stack[i] + ' ';
if (handler) {
handler(that.stack[i]);
}
}
}
console.log('棧內所有元素為 stackStr = ' + stackStr);
};
};
// 測試case
var ins = new Stack(5);
ins.push('h');
ins.push('e');
ins.push('l');
ins.push('l');
ins.push('o');
ins.pop();
// ins.clearStack();
console.log('棧是否為空 = ' + ins.isStackEmpty());
console.log('棧是否為滿 = ' + ins.isStackFull());
console.log('當前棧長度 = ' + ins.getStackLength());
ins.traverseStack();