栈,是一种后入先出(LIFO)的线性结构。栈的头部,称为栈底;栈的尾部,称为栈顶。元素,从栈顶压入;从栈顶弹出。
如何实现一个栈:
(1)确定存储结构:是离散的,还是连续的。进而言之,是链表,还是连续表。绝大多数的编程语言中,其数据结构,不一定实现链表,但都会实现数组(Array)。可以选用数组,作为存储结构。
(2)确定操作方法:需要实现入栈方法(push),出栈方法(pop),预览栈顶方法(peek),清栈方法(clear),获取栈高方法(length)。
具体实现:
#!/usr/bin/node
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = function ( element ) {
this.dataStore[this.top++] = element;
};
this.pop = function () {
return this.dataStore.splice(--this.top,1)[0];
};
this.peek = function () {
return this.dataStore[this.top-1];
};
this.length = function () {
return this.top;
};
this.clear = function () {
delete this.dataStore;
this.dataStore = [];
this.top = 0;
}
};