栈简单介绍-《数据结构与算法》

来源:互联网 发布:乡镇网络舆情应急预案 编辑:程序博客网 时间:2024/05/21 05:18
//栈是一种后入先出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());
原创粉丝点击