JavaScript實現佇列(程式碼+測試)

hlj20172746發表於2020-12-09

程式碼

<script>
        function Queue() {
            this.dataStore = [];
        }

        Queue.prototype.enqueue = function (data) {
            this.dataStore.push(data)
        }
        Queue.prototype.dequeue = function () {
            if (!this.empty()) {
                return this.dataStore.shift();
            } else {
                console.log('佇列為空,無法出隊');
            }
        }
        Queue.prototype.front = function () {
            if (!this.empty()) {
                return this.dataStore[0];
            } else {
                console.log('佇列為空');
            }
        }
        Queue.prototype.back = function () {
            if (!this.empty()) {
                return this.dataStore[this.dataStore.length - 1];
            } else {
                console.log('佇列為空');
            }
        }
        Queue.prototype.toString = function () {
            let str = '';
            for (let i = 0; i < this.dataStore.length; i++) {
                str += this.dataStore[i] + ' ';
            }
            return str;
        }
        Queue.prototype.empty = function () {
            if (this.dataStore.length == 0) {
                return true;
            } else {
                return false;
            }
        }
    </script>

測試

<script>
        let queue = new Queue();
        for (let i = 0; i < 5; i++) {
            queue.enqueue(i);
        }
        console.log(queue.toString());

        for (let i = 0; i < 5; i++) {
            console.log('佇列頭為');
            console.log(queue.front());
            console.log('佇列尾為:');
            console.log(queue.back());
            queue.dequeue(i);
        }
        queue.dequeue();
        queue.front();
        queue.back();
    </script>

相關文章