loading...

js 数据结构学习之栈

  • 实例:二进制转换
    divide(decNumber,base){
      const items = new WeakMap();
      class Stack {
        constructor(){
          items.set(this, []);
        }
        push(element){
          let s = items.get(this);
          s.push(element);
        }
        pop(){
          let s = items.get(this);
          let r = s.pop();
          return r;
        }
        peek(element){
          let s = items.get(this);
          return s[s.length -1];
        }
        isEmpty(element){
          let s = items.get(this);
          return s.length == 0;
        }
        size(element){
          let s = items.get(this);
          return s.length;
        }
        clear(element){
          let s = items.get(this);
          s = [];
        }
        print(element){
          let s = items.get(this);
          console.log(s.toString());
        }
      }

      var remStack = new Stack(),rem,baseString = '',digits = '0123456789ABCDEF';
      while(decNumber > 0){
        rem = Math.floor(decNumber % base);
        remStack.push(rem);
        decNumber = Math.floor(decNumber / base);
      }

      while(!remStack.isEmpty()){
        baseString += digits[remStack.pop()];
      }
      return baseString;
    }
posted @ 2021-01-20 22:36  robinloveslife  阅读(50)  评论(0编辑  收藏  举报