数据结构之栈结构

栈结构的特点是:“只能从栈的一端进入,先进后出”。

利用JS的数组来模拟栈结构:

function Stack(params) {
      //
      this.items = [];
    }
    // 实现栈方法
    // 1、入栈
    Stack.prototype.push = function (element) {
      this.items.push(element);
    }
    // 2、出栈
    Stack.prototype.pop = function () {
      if (this.isEmpty()) {
       return null;
      }
      //
      return this.items.pop();
    }
    // 3、查看栈顶元素
    Stack.prototype.peek = function () {
      if (this.isEmpty()) {
        return null;
      }
      //
      return this.items[0];
    }
    // 4、栈里面元素的数量
    Stack.prototype.size = function () {
      return this.items.length;
    }
    // 5、栈是否为空
    Stack.prototype.isEmpty = function () {
      return this.items.length === 0;
    }
    // 6、栈的toString方法
    Stack.prototype.toString = function (params) {
      if (this.isEmpty()) {
        return ''
      }
      let result = '';
      for (let i = 0; i < this.items.length; i++) {
        const element = this.items[i];
        result += element + ''
      }

      return result;
    }

  利用栈结构可以实现十进制转为二进制,代码如下:

   function decToBin(decNumber) {
      const stack = new Stack();
      while (decNumber > 0) {
        stack.push(decNumber%2);
        decNumber = Math.floor(decNumber/2)
      }
      let binaryStr = '';
      
      while (stack.size() > 0) {
        binaryStr +=  stack.pop() + '';
      }
      return binaryStr;
   }

  因为作为学习使用,以上代码没有考虑浏览器兼容和一些边界问题,如果作为业务上使用的话,需要进一步加上一些边界处理的代码,以便程序更加稳定。

posted @ 2021-10-14 13:31  闯入码途的水产人  阅读(73)  评论(0编辑  收藏  举报