栈结构的基本实现

栈是遵循先进后出的方式,新元素和待删除的元素都放在栈的顶端。旧的元素都放在栈底
类似放书本一样,一摞书中我们一般都是从上(栈顶)放书或者从上面拿书

功能描述

  • push 方法想栈堆中添加新元素
  • pop删除元素
  • peek查询栈顶的元素
  • print 查询栈中每一个元素
  • isEmpty判断栈是否尾空
  • clear清空栈

代码实现


class Stack {
    constructor() {
        this._key = 0;
        this._size = 0;    
        this._length = 0;
        this._stackObj = {};    
    }
    // 从栈尾删除 返回删除后的站栈
    pop() {
        if (this.isEmpty()) return [];
        this._delete();
        return this._stackObj;
    }
   //内置的删除的方法
    _delete() {
        const arr =Object.keys(this._stackObj);
        const lastKey = arr.pop();
         delete this._stackObj[lastKey];
         this._key --;
         this._length --;
    }
    _keys(){
        return Object.keys(this._stackObj);
    }
    // 从后添加
    push(value) {
        this._stackObj[this._key] = value;
        this._key++;
        this._size++;
        this._length++;
        return this._stackObj;
    }
    isEmpty() {
        return this._size === 0;
    }
    //清空
    clear() {
        this._size = 0;
        this._key = 0;
        this._stackObj = {};
    }
    toString() {
        let str = '';
        if (this.isEmpty()) return str;
        this._keys.forEach(key => {
            str = `${this._stackObj[key]}`
            console.log(str);
        });
    }
    // 查看栈顶的元素的值
    peek() {
        if (this.isEmpty())return;
        return this._stackObj[this._keys().pop()];
    }
    print() {
      if (this.isEmpty()) return null;
      this._keys.forEach(key=>{
      	console.log(this._stackObj[key]
      });
    }
}
const s = new Stack();
s.push('xue');
s.push('name')
// console.dir(s.push('xie'));
console.log(s.peek());
console.log(s.pop());
console.log(s);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值