1. 程式人生 > >數據結構與算法 ----- 隊列

數據結構與算法 ----- 隊列

body span turn gpo pty 頂部 清空 幾種操作 items

  隊列和棧類似,也是一種集合,只不過它遵循的原則是先進先出,這很好理解,想一想ATM機取款就可以了。先到的人,先取款,後面到的人只能等前面的人取款成功。所以隊列的操作是從前面刪除元素,後面插入元素,其它則和棧沒有什麽區別。它有以下幾種操作:

  插入(enqueue):把一個元素插入到隊列的後面;

  刪除(dequeue): 把一個元素從隊列的頂部刪除;

  取出隊列頂部的元素(front): 返回隊列的頂部的元素;

  判隊列空(isEmpty): 判斷隊列是否為空;

  清空隊列(clear):把隊列中所有的元素刪除;

  隊列的大小(size):返回隊列中元素的個數;

  實現方式還是用數組

function queue() {
    let items = [];

    this.enqueue = function(elem) {     // 隊列尾部添加元素
        items.push(elem);
    }
    this.dequeue = function(elem) {     // 隊列頭部刪除元素
        return items.shift();
    }

    this.front = function () {           // 返回隊列中的第一個元素
        return items[0];
    }

    
this.isEmpty = function() { // 隊列是否為空 return items.length === 0; } this.size = function() { // 隊列的大小 return items.length; } this.print = function() { // 打印隊列 console.log(items); } } // es6 的原型鏈方式 let queue2 = (function() { const items
= new WeakMap(); class Queque { constructor(){ items.set(this, []); } enqueue(elem) { let q = items.get(this); q.push(elem); } dequeue() { let q = items.get(this); return q.shift(); } front() { let q = items.get(this); return q[0]; } isEmpty() { return items.get(this).length === 0; } size() { return items.get(this).length; } clear() { items.set(this, []); } print() { console.log(items.get(this)) } } return Queque; })()

  優先隊列

  

數據結構與算法 ----- 隊列