数据结构与算法(一):栈

1. 概述

栈结构是一种非常常见的的数据结构,在程序中应用广泛。就比如我们平常所说的基本数据类型存在栈中。

简单描述:栈就是一个盒子,只有一个入口,从入口放入,从入口取出。
在这里插入图片描述
如图:
push:入栈
pop: 出栈
从图可知压入栈的顺序123,而出栈顺序只能为321

可知栈的特点:
先进后出,后进先出


2. 封装一个栈

这里以封装一个数组为例
实现方法:push()、pop()、查看栈顶、判断是否为空、获取栈中元素个数、toString

 function Stack() {
      this.items = [];
      // 1.push
      Stack.prototype.push = function (item) {
        // this.items.push(item)
        this.items[this.items.length] = item
      }
      // 2.pop
      Stack.prototype.pop = function () {
        return this.items.pop()
      }
      // 3.查看栈顶
      Stack.prototype.peek = function () {
        return this.items[this.items.length-1]
      }
      // 4.判断是否为空
      Stack.prototype.isEmpty = function () {
        return this.items.length === 0
      }
      // 5.获取栈中元素个数
      Stack.prototype.nums = function () {
        return this.items.length;
      }
      // 6.toString
      Stack.prototype.toString = function () {
        return this.items.join(' ')
      }
    }

验证

let sta = new Stack();
sta.push('a');
sta.push('b');
sta.push('c');
sta.push('d');
console.log(sta);
console.log(sta.peek());
console.log(sta.isEmpty());
console.log(sta.nums());
console.log(sta.toString());

在这里插入图片描述


3. 实例(十进制转二进制)

分析: 十进制转二进制:除2取余,余数从后往前取
联系: 将余数依次入栈,出栈刚好是从后往前取

  <script>
    function TentoTwo(num) {
      let arr = [];
      let newarr = [];
      if (num === 0)
        arr.push(0)
      while (num !== 0) {
        arr.push(num % 2)
        num = Math.floor(num / 2);
      }
      while (arr.length > 0) {
        newarr.push(arr.pop());
      }
      console.log(newarr);
    }
    TentoTwo(25)
  </script>

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值