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;  
    }  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM