栈与队列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

相关文章:

  • 2021-04-30
  • 2021-06-08
  • 2022-12-23
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2021-05-13
猜你喜欢
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2021-05-25
  • 2021-08-28
  • 2021-10-30
  • 2022-12-23
相关资源
相似解决方案