• js练习-两个栈实现队列


    目录

    现在有个Q队列和栈A,栈B,栈只有两个方法,push()和pop(), 队列也只有两个方法,push()和pull(),队列的进和出都只能通过A和B的push和pop实现。
    
    // 大概举个例子
    const Q = {
    
        a = new A(),
        b = new B(),
    
        push() {
    
        },
    
        pull() {
    
        }
    }
    

    const Q = {
      a: [], // 先放
      b: [], // 后放
    
      push(value) {
        const lengthA = this.a.length;
        const lengthB = this.b.length;
        if (lengthA === lengthB) {
          this.a.push(value);
        } else {
          this.b.push(value);
        }
        return lengthA + lengthB + 1;
      },
    
      pull() {
        const lengthA = this.a.length;
        if (!lengthA) return undefined;
    
        const func = (popArray, pushArray, forLength) => {
          for (let i = 0; i < forLength; i++) {
            const value = popArray.pop();
            pushArray.push(value);
          }
        };
    
        func(this.a, this.b, lengthA - 1);
        const result = this.a.pop();
        func(this.b, this.a, lengthA - 1);
    
        const { a } = this;
        this.a = this.b;
        this.b = a;
    
        return result;
      },
    };
    Q.push('a');
    Q.push('b');
    Q.push('c');
    Q.pull(); // a
    Q.pull(); // b
    Q.pull(); // c
    
  • 相关阅读:
    技术博客之Saju M
    Dajax 的安装以及详细使用
    当我感觉厌倦的时候
    2014年3月22日 星期日
    windows 7远程桌面访问 ubuntu12.04
    promise的用法
    for循环中匿名同步
    开启Group Work Site功能
    Jquery根据属性模糊查询节点
    设置用户字段
  • 原文地址:https://www.cnblogs.com/qiqi715/p/10422130.html
Copyright © 2020-2023  润新知