关于javascript:数据结构JavaScript-Queue-实现

51次阅读

共计 924 个字符,预计需要花费 3 分钟才能阅读完成。

残缺可运行代码

class Queue {constructor() {
    this.count = 0
    // 队头
    this.head = 0
    this.items = {}}

  enqueue(element) {this.items[this.count] = element
    this.count++;
  }

  dequeue() {if (this.isEmpty()) {return undefined;}
    const result = this.items[this.head]
    delete this.items[this.head]
    this.head++
    return result
  }

  peek() {if (this.isEmpty()) {return undefined}
    return this.items[this.head]
  }

  isEmpty() {return this.size() === 0
  }

  clear() {this.items = {}
    this.count = 0
    this.head = 0
  }

  size() {return this.count - this.head}

  toString() {if (this.isEmpty()) {return ''}
    let objString = `${this.items[this.head]}`
    for (let i = this.head + 1; i < this.count; i++) {objString = `${objString},${this.items[i]}`
    }
    return objString
  }
}
// 
const queue = new Queue()

queue.enqueue('a')
queue.enqueue('b')
queue.enqueue('c')
queue.enqueue('d')
console.log(queue.toString()) //--> a,b,c,d

queue.dequeue()
queue.dequeue()
console.log(queue.toString()) //--> c,d

console.log(queue.peek()) //--> c

console.log(queue.isEmpty()) //--> false

console.log(queue.size()) //--> 2

正文完
 0