栈是一种遵从后进先出(LIFO)原则的有序集合。新添加的或待删除的元素都保存在栈的 末尾,称作栈顶,另一端就叫栈底。在栈里,新元素都靠近栈顶,旧元素都接近栈底。
举个栗子,差不多这样子。。。
栈的创建
使用数组创建的栈
function Stack(){//首先,申明一个类
var item = []; //使用一种数据结构来保存栈内元素
//声明常用方法
this.push = function(v){//添加一个(或几个)新元素到栈顶
item.push(v);
}
this.pop = function(){//移除栈顶的元素,同时返回被移除的元素
return item.pop();
}
this.peek = function(){//返回栈顶的元素,不对栈做任何修改
return item[item.length-1];
}
this.isEmpty = function(){//如果栈里没有任何元素就返回true,否则返回false
return !item.length;
}
this.clear = function(){//移除栈里的所有元素
item = [];
}
this.size = function(){//返回栈里的元素个数
return item.length;
}
this.print = function(){
console.log(item.toString());
}
}
使用链表创建的链栈
function Stack(){//首先,申明一个类
//使用链表节点来保存栈内元素
var Node = function(value){
this.value = value;
this.next = null;
}
//初始化栈的高度以及栈顶指针
var length = 0;
var top = null;
//声明常用方法
this.push = function(v){//添加一个(或几个)新元素到栈顶
var newNode = new Node(v);
if(!top){
top = newNode;
}else{//头插
newNode.next = top;
top = newNode;
}
length++;
return top;
}
this.pop = function(){//移除栈顶的元素,同时返回被移除的元素
if (!top) {
alert("Empty stack");
return ;
} else{
var t = top;
top = top.next;
t.next = null;
length--;
return top;
}
}
this.peek = function(){//返回栈顶的元素,不对栈做任何修改
return top.value;
}
this.isEmpty = function(){//如果栈里没有任何元素就返回true,否则返回false
return !length;
}
this.clear = function(){//移除栈里的所有元素
top = null;
length = 0;
return top;
}
this.size = function(){//返回栈里的元素个数
return length;
}
this.print = function(){
var t = top;
var result = [];
while(t){
result.unshift(t.value);
t = t.next;
}
console.log(result);
return;
}
}
栈的基本使用
var stack = new Stack();
console.log(stack.isEmpty()); //true
stack.push(1);
stack.push(2);
console.log(stack.size()); //2
stack.push(3);
console.log(stack.peek()); //3
stack.pop();
stack.print(); //1,2
stack.clear();
console.log(stack.isEmpty()); //true