栈的定义
栈是一种只能在一端进行插入或删除操作的线性表。其中允许进行插入或删除操作的一端称为栈顶(Top)。表的另一端称为栈底,栈底是固定不变的。栈的插入和删除操作一般称为入栈和出栈。
特点:先进后出(FILO)。
栈的结构
顺序栈:用js内置对象Array实现
function ArrayStack(){
var arr = [];
//压栈操作
this.push = function(element){
arr.push(element);
}
//退栈操作
this.pop = function(){
return arr.pop();
}
//获取栈顶元素
this.top = function(){
return arr[arr.length-1];
}
//获取栈长
this.size = function(){
return arr.length;
}
//清空栈
this.clear = function(){
arr = [];
return true;
}
this.toString = function(){
return arr.toString();
}
}
链式栈
const OK = true;
const ERROR = false;
const {log} = console;
// 链表结点
class LNode {
constructor (data) {
this.data = data;
this.next = null;
}
}
class LinkStack {
constructor() {
this.data = null;
this.next = null;
}
isEmpty () {
if(this.next === null) {
return OK;
} else {
return ERROR;
}
}
push (elem) {
const p = new LNode(elem);
p.next = this.next;
this.next = p;
return OK;
}
pop () {
const p = this.next;
if (p === null) return ERROR;
this.next = p.next;
return p.data;
}
}
const p = new LinkStack();
p.push(1);
p.push(2);
p.push(3);
log(JSON.stringify(p));
let x = p.pop()
log(x,JSON.stringify(p))