• 栈的实现:

    class Stack {
      constructor() {
        this.store = [];
        this.top = 0;
      }
    
      push(item) {
        this.store[this.top++] = item;
        return this.store;
      }
    
      pop() {
        return this.store[--this.top];
      }
    
      peek() {
        return this.store[this.top - 1];
      }
    
      size() {
        return this.top;
      }
    
      claer() {
        this.store = [];
        this.top = 0;
      }
    }
    
    const stack = new Stack();
    
    stack.push('shang');
    stack.push('yy');
    console.log(stack.push('big'));
    console.log(stack.peek());
    console.log(stack.size());

    二、栈的应用

    // 进制转换 10进制转换成其他进制
    
    function dataconverse(data, base) {
      const stack = [];
      let num = data;
      do {
        stack.push(num % base);
        num = Math.floor(num / base);
      } while (num > 0);
      return stack.reduceRight((per, cur) => {
        return per + cur;
      }, '');
    }
    const result = dataconverse(125, 8);
    console.log(result);
    
    // 判断是回文
    function isPalindrome(word) {
      const stack = [];
      for (let i = 0; i < word.length; i++) {
        stack.push(word[i]);
      }
      return stack.join('') === word;
    }
    
    console.log(isPalindrome('1001'));
    function isPalindrome1(word) {
      return (
        word
          .split('')
          .reverse()
          .join('') === word
      );
    }
    console.log(isPalindrome1('110011'));
  • 相关阅读:
    nyoj-707-A Simple Problem
    nyoj-290-动物统计加强版
    nyoj-27-水池数目
    nyoj-92-图像有用区域
    nyoj-82-迷宫寻宝(一)
    nyoj-289-苹果
    nyoj-311-完全背包
    Docker: docker network 容器网络
    Docker: docker container常用命令实战(2)-数据持久化
    Docker: docker container常用命令实战
  • 原文地址:https://www.cnblogs.com/shangyueyue/p/10911809.html
Copyright © 2020-2023  润新知