//栈是一种后入先出LIFO,last-in-first-out的数据结构
//所以任何不在栈顶的元素都无法访问,对栈的操作主要是将元素压入push和弹出pop;peek用于查看栈顶的元素;
//定义stack类的构造函数,和相关操作;
function Stack(){
this.dataStore=[];
this.top=0;
this.push=push;
this.pop=pop;
this.peek=peek;
this.clear=clear;
this.length=length;
}
function push(element){
return this.dataStore[this.top++]=element;
}
function pop(element){
return this.dataStore[--this.top];
}
function peek(element){
return this.dataStore[this.top-1]
}
//有时候需要知道栈内有多少元素
function length(){
return this.top
}
//将栈内元素清空
function clear(){
this.top=0;
}
//测试实现的代码
var s=new Stack();
s.push("David");
s.push("raymond");
s.push("bryan");
console.log(s.length());
console.log(s.peek());
var popped= s.pop();
console.log("删除的元素是:"+popped,"s的长度是:"+s.length());
s.push("Cythia");
console.log("顶部的元素是:"+s.peek(), "s的长度是:"+s.length());
栈简单介绍-《数据结构与算法》
最新推荐文章于 2021-11-04 13:44:28 发布