在數據結構與算法中,棧
stack
又名堆棧,棧是一種受限的線性儲存結構,只容許在一端加入元素和刪除元素。這一端稱爲棧頂,加入元素稱做入棧、壓棧、進棧;刪除元素又稱做出棧、退棧。被刪除元素的相鄰元素會從新稱爲棧頂元素。棧遵循先進後出FILO
的規則。git
在編程語言中不少時候使用到棧的數據結構。例如函數棧結構。A函數調用B函數,B函數調用了C函數。語言執行先會把A函數、B函數、C函數依次進棧;待C函數執行完成出棧,B函數出棧,最後A函數完成出棧。github
push(element)
:push是進棧操做,其中element是須要進棧的元素,返回操做成功與否布爾值。pop()
:pop移除棧頂元素操做,返回移除的棧頂元素。size()
:獲取棧中的棧元素數量,返回一個數字。isEmpty()
:判斷棧是否爲空,返回一個布爾值。peek()
:返回棧頂元素,但不移除棧頂元素。bottom()
:返回棧底元素。clear()
:清除全部棧元素,返回操做成功與否布爾值。class Stack {
constructor() {
this.lists = [];
}
size() {
return this.lists.length;
}
isEmpty() {
return this.lists.length === 0;
}
peek() {
const topIndex = this.size() - 1;
return this.lists[topIndex];
}
bottom() {
return this.lists[0];
}
push(element) {
this.lists.push(element);
return true;
}
pop() {
return this.lists.pop();
}
clear() {
this.lists = [];
return true;
}
toString() {
let result = "";
this.lists.forEach(value => {
result = result + "" + value;
});
return result;
}
}
複製代碼
經過ES5把功能函數能夠綁定在對象的實例上,也能夠把功能函數加在函數的原型鏈上算法
function Stack() {
this.lists = [];
}
Stack.prototype.push = function (element) {
this.lists.push(element);
return true;
}
Stack.prototype.pop = function () {
return this.lists.pop();
}
Stack.prototype.clear = function () {
this.lists = [];
return true;
}
Stack.prototype.peek = function () {
var topIndex = this.size() - 1;
return this.lists[topIndex];
}
Stack.prototype.size = function () {
return this.lists.length;
}
Stack.prototype.isEmpty = function () {
return this.lists.length === 0;
}
Stack.prototype.bottom = function () {
return this.lists[0];
}
Stack.prototype.toString = function () {
var result = "";
for (var i = 0; i < this.lists.length; i++) {
result = result + '' + this.lists[i];
}
return result;
}
複製代碼
ES5和ES6實現棧結構已經經過了測試可運行。上面是經過數組實現的棧結構,其實鏈表也能夠實現棧結構。下面數據結構鏈表篇會使用鏈表實現棧的數據結構
github地址: github.com/Harhao編程