JS实现队列

JS实现队列:

队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头

链式队列的实现

function LinkedQueue() {
    let Node = function (ele) {
        this.ele = ele;
        this.next = null;
    }

    let length = 0,
        front, //队首指针
        rear; //队尾指针
    this.push = function (ele) {
        let node = new Node(ele),
            temp;

        if (length == 0) {
            front = node;
        } else {
            temp = rear;
            temp.next = node;
        }
        rear = node;
        length++;
        return true;
    }

    this.pop = function () {
        let temp = front;
        front = front.next
        length--;
        temp.next = null
        return temp;
    }

    this.size = function () {
        return length;
    }
    this.getFront = function () {
        return front;
        // 有没有什么思路只获取队列的头结点,而不是获取整个队列
    }
    this.getRear = function () {
        return rear;
    }
    this.toString = function () {
        let string = '',
            temp = front;
        while (temp) {
            string += temp.ele + ' ';
            temp = temp.next;
        }
        return string;
    }
    this.clear = function () {
        front = null;
        rear = null;
        length = 0;
        return true;
    }
}

let myQueue = new LinkedQueue();

myQueue.push(1)
myQueue.push(2)
myQueue.push(3)
myQueue.push(4)
console.log(myQueue.toString()) // 1 2 3 4 
console.log(myQueue.pop()) // Node { ele: 1, next: null }
console.log(myQueue.toString()) // 2 3 4

顺序存储队列:利用js内置Array对象

function ArrayQueue(){  
    var arr = [];  
        //入队操作  
    this.push = function(element){  
        arr.push(element);  
        return true;  
    }  
        //出队操作  
    this.pop = function(){  
        return arr.shift();  
    }  
        //获取队首  
    this.getFront = function(){  
        return arr[0];  
    }  
        //获取队尾  
    this.getRear = function(){  
        return arr[arr.length - 1]  
    }  
        //清空队列  
    this.clear = function(){  
        arr = [];  
    }  
        //获取队长  
    this.size = function(){  
        return length;  
    }  
}  

 

posted @ 2018-11-01 19:23  .追风逐月  阅读(22754)  评论(0编辑  收藏  举报