JavaScript數據結構雜談(雙端隊列)

雙端隊列是與隊列相似的項的有序集合,其實本質就是隊列,只不過是前端與後端都支持插入和刪除操做的隊列,更實用,因此也就不存在先進先出這種說法了。

咱們能夠經過數組來實現,可是爲了寫出一個更高效得數據結構,使用對象來實現。javascript

class Deque{
    constructor(){
        this.count= 0;
        this.lowestCount = 0;
        this.items = {};
    }
    isEmptry(){
        return this.size() === 0;
    }
    size(){
        return this.count - this.lowestCount;
    }
    clear(){
        this.count= 0;
        this.lowestCount = 0;
        this.items = {};
    }
    toString(){
        if(this.isEmptry()){
            return '';
        }
        let objString = `${this.items[this.lowestCount]}`;
        for (let i=this.lowestCount+1;i<this.count;i++) {
            objString = `${objString},${this.items[i]}`;
        }
        return objString;
    }
    addBack(el){
        this.item[this.count]=el;
        this.count++;
    }
    addFront(el){
        if(this.isEmptry()){
            this.addBack(el);
        }else if(this.lowestCount>0){
            this.lowestCount--;
            this.item[this.lowestCount]=el;
        }else{
            for(let i=this.count;i>0;i--){
                this.item[i]=this.item[i-1];
            }
            this.count++;
            this.lowestCount=0;
            this.item[0]=el;
        }
    }
    removeFront(){
        if(this.isEmptry()){
            return undefined;
        }
        let c = this.items[this.lowestCount];
        delete this.items[this.lowestCount];
        this.lowestCount++;
        return c;
    }
    removeBack(){
         if (this.isEmpty()) {
            return undefined;
         }
         this.count--;
         let c = this.items[this.count];
         delete this.items[this.count];
         return c;
    }
    peekFront() {
        if (this.isEmpty()) {
            return undefined;
        }
        return this.items[this.lowestCount];
    }
    peekBack() {
        if (this.isEmpty()) {
            return undefined;
        }
        return this.items[this.count - 1];
    }
 }

該內容借鑑於學習javascript數據結構與算法。前端

相關文章
相關標籤/搜索