stack的第一種含義是一組數(shù)據(jù)的存放方式,特點(diǎn)為L(zhǎng)IFO,即后進(jìn)先出(Last in, first out)。
分析stack的特點(diǎn):
- push:在最頂層加入數(shù)據(jù)。
- pop:返回并移除最頂層的數(shù)據(jù)。
- top:返回最頂層數(shù)據(jù)的值,但不移除它。
/**
* @file Stack.js
* @desc 用js實(shí)現(xiàn)stack數(shù)據(jù)結(jié)構(gòu)
*
* *************************
* 用法:
* var stack = new Stack();
* stack.push([1,2,3]);
* stack.push('xxxxx');
* var all = stack.displayAll();
* console.log(all);
*
* *************************
*/
function Stack() {
// 返回最后插入的一個(gè)數(shù)據(jù)
this.top = null;
// 返回棧內(nèi)數(shù)據(jù)的長(zhǎng)度
this.size = 0;
}
Stack.prototype = {
constructor: Stack,
// 插入一個(gè)數(shù)據(jù),放在棧的最后一個(gè)位置
push: function (data) {
var node = {
data: data,
next: null
};
node.next = this.top;
this.top = node;
this.size++;
},
// 返回最后的一個(gè)數(shù)據(jù)
peek: function () {
return this.top === null ? null : this.top.data;
},
// 從棧里取出最后的一個(gè)數(shù)據(jù),與peek的區(qū)別:peek只讀取,pop返回并移除最頂層的數(shù)據(jù)
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;
},
// 清楚棧內(nèi)的數(shù)據(jù)
clear: function () {
this.top = null;
this.size = 0;
},
// 顯示站內(nèi)的所有數(shù)據(jù)
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;
}
};