zoukankan      html  css  js  c++  java
  • JavaScript实现基于对象的双端队列

    class Deque {
      constructor() {
        this.count = 0;
        this.lowestCount = 0;
        this.items = {};
      }
    
      addFront(element) {
        if (this.isEmpty()) {
          this.addBack(element);
        } else if (this.lowestCount > 0) {
          this.lowestCount--;
          this.items[this.lowestCount] = element;
        } else {
          for (let i = this.count; i > 0; i--) {
            this.items[i] = this.items[i - 1];
          }
          this.count++;
          this.items[0] = element;
        }
      }
    
      addBack(element) {
        this.items[this.count] = element;
        this.count++;
      }
    
      removeFront() {
        if (this.isEmpty()) {
          return undefined;
        }
        const result = this.items[this.lowestCount];
        delete this.items[this.lowestCount];
        this.lowestCount++;
        return result;
      }
    
      removeBack() {
        if (this.isEmpty()) {
          return undefined;
        }
        this.count--;
        const result = this.items[this.count];
        delete this.items[this.count];
        return result;
      }
    
      peekFront() {
        if (this.isEmpty()) {
          return undefined;
        }
        return this.items[this.lowestCount];
      }
    
      peekBack() {
        if (this.isEmpty()) {
          return undefined;
        }
        return this.items[this.count - 1];
      }
    
      isEmpty() {
        return this.size() === 0;
      }
    
      clear() {
        this.items = {};
        this.count = 0;
        this.lowestCount = 0;
      }
    
      size() {
        return this.count - this.lowestCount;
      }
    
      toString() {
        if (this.isEmpty()) {
          return '';
        }
        let objString = `${this.items[this.lowestCount]}`;
        for (let i = this.lowestCount + 1; i < this.count; i++) {
          objString = `${objString},${this.items[i]}`;
        }
        return objString;
      }
    }
  • 相关阅读:
    PHP面向对象之原型(trait)
    PHP面向对象之命名空间
    Javascript中的Copy()函数
    六、unique_lock取代lock_guard
    五、互斥量
    四、创建和等待多个线程
    三、线程传参
    二、线程的启动与结束 join与detach
    HTTP:常见状态码
    HTTP:简述URL、URN和URI
  • 原文地址:https://www.cnblogs.com/WP-WangPin/p/13896221.html
Copyright © 2011-2022 走看看