JavaScript 实现队列操作

Queue.isEmpty =  function() {
    return (this.front ==  this.rear);
}
Queue.isFull = function() {
    return ((this.rear + 1) % this.MaxSize == this.front);
}
Queue.push = function(element) {
    if (this.isFull()) {
        console.error('队列已满');
        return -1
    }
    let index = (++this.rear) % this.MaxSize;
    this.queue[index] = element;
}
Queue.pop = function() {
    if (this.isEmpty()) {
        console.error('队列为空');
        return -2;
    }
    let index = (++this.front) % this.MaxSize;
    let element = this.queue[index];
    this.queue[index] = null;
    return element;
}
function Queue(MaxSize) {
    this.MaxSize = MaxSize;
    this.front = this.rear = 0;
    this.queue = new Array(this.MaxSize);
    this.push = Queue.push;
    this.pop = Queue.pop;
    this.isEmpty = Queue.isEmpty;
    this.isFull = Queue.isFull;
}

 

posted @ 2020-06-23 17:28  guogrant  阅读(598)  评论(0编辑  收藏  举报