stack的第一種含義是一組數據的存放方式,特點為LIFO,即后進先出(Last in, first out)。
分析stack的特點:
- push:在最頂層加入數據。
- pop:返回并移除最頂層的數據。
- top:返回最頂層數據的值,但不移除它。
/**
* @file Stack.js
* @desc 用js實現stack數據結構
*
* *************************
* 用法:
* var stack = new Stack();
* stack.push([1,2,3]);
* stack.push('xxxxx');
* var all = stack.displayAll();
* console.log(all);
*
* *************************
*/
function Stack() {
// 返回最后插入的一個數據
this.top = null;
// 返回棧內數據的長度
this.size = 0;
}
Stack.prototype = {
constructor: Stack,
// 插入一個數據,放在棧的最后一個位置
push: function (data) {
var node = {
data: data,
next: null
};
node.next = this.top;
this.top = node;
this.size++;
},
// 返回最后的一個數據
peek: function () {
return this.top === null ? null : this.top.data;
},
// 從棧里取出最后的一個數據,與peek的區別:peek只讀取,pop返回并移除最頂層的數據
pop: function () {
if (this.top === null) return null;
var out = this.top;
this.top = this.top.next;
if (this.size > 0) this.size--;
return out.data;
},
// 清楚棧內的數據
clear: function () {
this.top = null;
this.size = 0;
},
// 顯示站內的所有數據
displayAll: function () {
if (this.top === null) return null;
var arr = [];
var current = this.top;
for (var i = 0, len = this.size; i < len; i++) {
arr[i] = current.data;
current = current.next;
}
return arr;
}
};