一個用JS數組實現的隊列


一個用JS數組實現的隊列
/*一個用數組實現的隊列*/
function Queue(){
    this.dataStore = [];//存放隊列的數組,初始化為空
    this.enqueue = enqueue;//向隊列尾部添加一個元素
    this.dequeue = dequeue;//刪除隊首的元素
    this.theFront = theFront;//讀取隊首的元素
    this.back = back;//對取隊尾的元素
    this.toStrings = toStrings;//顯示隊列內的所有元素
    this.empty = empty;//判斷隊列是否為空
}

function enqueue(element){
    this.dataStore.push(element);
}

function dequeue(){
    this.dataStore.shift();
}

function theFront(){
    return this.dataStore[0];
}

function back(){
    return this.dataStore[this.dataStore.length-1];
}

function toStrings(){
    return this.dataStore;
}

function empty(){
    if(this.dataStore.length == 0){
       return true;
    }else{
        return false;
    }
}

/*測試程序*/
var q = new Queue();
q.enqueue("aa");
q.enqueue("bb");
q.enqueue("cc");
console.log(q.toStrings());//[ 'aa', 'bb', 'cc' ]
q.dequeue();
console.log(q.toStrings());//[ 'bb', 'cc' ]
console.log(q.theFront());//bb
console.log(q.back());//cc

 


免責聲明!

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



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