JS数据结构与算法(每周一篇)--栈

  • 相对于数组在删除和添加数据的时候更为可控
  • 先进后出,后进先出

这个像落书一样,后落上去的书,先拿下去

书

栈的数据结构

    • push:添加栈顶
    • pop:移除栈顶
    • peek:但会栈顶元素
    • isEmpty:是否为空
    • clear:晴空万里
    • size:大小
// es5
function Stack(){
    let items= []
    this.push=function(elements){
        items.push(elements)
    }
    this.pop=function(){
        return items.pop();
    }
    this.peek=function(){
        return items[items.length-1]
    }
    this.isEmpty=function(){
        return items.length == 0
    }
    this.size=function(){
        return items.length
    }
    this.clear=function(){
        items = []
    }
    this.print=function(){
        console.log(items.toString())
    }
}

现在都2020年了es6多少得摸一下

// es6 会暴露iterm
/*
* 节省内存
* 会暴露iterm,不能私有化,可被操作
*/
class Stack{
    constructor(){
        this.items=[]
    }
    push(elements){
        this.items.push(elements)
        console.log(this.items.toString())
    }
}
_items = Symbol()
class Stack{
    constructor(){
        this._items=[]
    }
    push(elements){
        this._items.push(elements)
        console.log(this.items.toString())
    }
}

栈能解决问题

  • 回溯问题(后面说)
  • 进制转化实例
// 转二进制
function divideBy2(decNumber){
    let stack = new Stack(),
    binaryString=''
    while(decNumber>0){
        stack.push(Math.floor(decNumber % 2))
        decNumber = Math.floor(decNumber / 2)
        console.log(decNumber)
    }
    while(!stack.isEmpty()){
        binaryString += stack.pop().toString()
    }
    return binaryString
}

// 转任意进制
// 突然发现这东西可以做加密🔐
function baseConverter(decNumber,base=2){
    let stack = new Stack(),
    baseString='',
    digits='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'
    while(decNumber>0){
        stack.push(Math.floor(decNumber%base))
        decNumber=Math.floor(decNumber/base)
    }
    while(!stack.isEmpty()){
        baseString+=digits[stack.pop()]
    }
    return baseString
}

以后遇到栈解决的题会在下面补充👏👏👏

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值