JavaScript 栈的数据结构实现

本小节实现的内容

创建我们自己的 JavaScript 数据结构库
栈数据结构
向栈添加元素
从栈移除元素
如何使用 Stack
十进制转二进制

1.栈数据结构

栈是一种遵从 后进先出 LIFO )原则的有序集合。新添加或待删除的元素都保存在栈的同
一端,称作栈顶,另一端就叫栈底。在栈里,新元素都靠近栈顶,旧元素都接近栈底。
一个存储东西小箱子 只有一端的出入 (就是说他只有一个口能出入)先存进去的东西 在最底部 ,最后存进去的东西在最顶部 取的时候只能从顶部开始取 所以 俗称先进后出,后进先出 

1.1 创建一个基于数组的栈

function Stack(){
    this.items=[]
}
//向栈里面添加一个元素

Stack.prototype.push=function (element){
    this.items.push(element)

}
//向栈里面移除元素
Stack.prototype.pop=function (){
    return this.items.pop()
}
// peek  查看栈顶元素

Stack.prototype.peek=function (){
    return this.items[this.items.length-1]
}
Stack.prototype.isEmpty=function (){
    return this.items.length ===0
}
Stack.prototype.size=function(){
    return this.items.length
}
Stack.prototype.clear=function (){
    this.items=[]
}
Stack.prototype.view_Elevments=function (){
    if(!this.isEmpty()){
      return   Array.prototype.join.call(this.items,",")

    }
}

let mystack=new Stack()
mystack.push(1)
mystack.push(2)
mystack.push(3)
console.log(mystack.isEmpty());
console.log(mystack.view_Elements());

1.2 创建一个基于对象的栈

function  Stack(){
    this.count=0
    this.items={}
}

 Stack.prototype.push=function (element){
    this.items[this.count]=element
     this.count++
 }
Stack.prototype.IsEmpty=function (){
    return (this.count===0)
}
Stack.prototype.get_length=function (){
    return this.count
}
Stack.prototype.pop=function (){
    if (this.IsEmpty()){
        return   undefined;
    }
    this.count--
    let element = this.items[this.count]
    delete this.items[this.count]
    return element
}
Stack.prototype.peek=function (){
     if (this.IsEmpty()){
        return   undefined;
    }
    return this.items[this.count-1]
}
Stack.prototype.clear=function (){
    this.count=0
    this.items={}
}

因为代码比较简单我就直接用代码实现了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值