1. 程式人生 > >演算法導論(第三版)練習 10.1-1 ~ 10.1-7 兩個棧實現佇列 兩個佇列實現棧

演算法導論(第三版)練習 10.1-1 ~ 10.1-7 兩個棧實現佇列 兩個佇列實現棧

棧與佇列js實現版本:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <script type="text/javascript">
            let log = console.log.bind(console);
            let x 
= [1, 2, 3]; x.isEmpty = function() { if (this.length == 0) { return true; } else { return false; } }; x.push(4); log("isEmpty", x.isEmpty()); // => isEmpty false
log(x); // => [1, 2, 3, 4] log(x.pop()); // => 4 log(x.pop()); // => 3 log(x.pop()); // => 2 log(x.pop()); // => 1 log(x.pop(), "??"); // => undefined ?? log("isEmpty", x.isEmpty()); // => isEmpty true
</script> <script type="text/javascript"> // 利用陣列Q[0..n](有效下標是0~n-1)實現一個最多容納n-1個元素的佇列 let queue = []; queue.size = 12; queue.tail = queue.head = 0; function enqueue(q, x) { let temp = (q.tail == q.size - 1) ? 0 : q.tail + 1; if (temp == q.head) { // 有效下標是12個的陣列,只能存11個數 throw new Error("overflow"); } else { q[q.tail] = x; q.tail = temp; } } function dequeue(q) { if (q.head == q.tail) { throw new Error("underflow"); } else { let x = q[q.head]; if (q.head == q.size - 1) { q.head = 1; } else { ++q.head; } return x; } } log(queue); for (let i = 0; i != queue.size - 1; ++i) { enqueue(queue, i); } log(queue); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, size: 12, head: 0, tail: 11] for (let i = 0; i != queue.size - 1; ++i) { log(dequeue(queue)); } dequeue(queue); // => Uncaught Error: underflow </script> </body> </html>
View Code

 

10.1-1

 

10.1-2

初始化:兩個指標分別指向0和x.length-1

push操作:首先檢查兩個是否相等,相等就丟擲overflow,不相等就賦值加1或者減1

 

10.1-3

 

10.1-4

 

10.1-5

調個api。。

        <script type="text/javascript">
            let arr = [1, 2, 3, 4];
            arr.push_back = function(x) {
                this.push(x);
            }
            arr.push_front = function(x) {
                this.unshift(x)
            }
            arr.pop_back = function() {
                return this.pop();
            }
            arr.pop_front = function() {
                return this.shift();
            }
            log(arr); // => [1, 2, 3, 4]
            arr.push_back(5);
            arr.push_front(0);
            log(arr); // => [0, 1, 2, 3, 4, 5]
            arr.pop_back();
            arr.pop_front();
            log(arr); // => [1, 2, 3, 4]
        </script>

 

10.1-6 & 10.1-7

不會做,不想做。。

大體思路參考:兩個棧實現佇列 兩個佇列實現棧