算法4 1.3.3 练习

题目:

 

    function Stack() {
            this.dataStore = []; //保存栈内元素,初始化为一个空数组
            this.top = 0; //栈顶位置,初始化为0
            this.push = push; //入栈
            this.pop = pop; //出栈
            this.peek = peek; //查看栈顶元素
            this.clear = clear; //清空栈
            this.length = length; //栈内存放元素的个数
            this.empty = empty; //栈内存放元素的个数
        }

        function empty() {
            if (this.top) {
                return false
            } else {
                return true
            }
        }

        function push(element) {
            this.dataStore[this.top++] = element;
        }

        function pop() {
            return this.dataStore[--this.top];
        }

        function peek() {
            return this.dataStore[this.top - 1];
        }

        function clear() {
            this.top = 0;
        }

        function length() {
            return this.top;
        }

        /*测试stack类的实现*/
        // var s = new Stack();
        // s.push("aa");
        // s.push("bb");
        // s.push("cc");
        // console.log(s.length()); //3
        // console.log(s.peek()); //cc
        // var popped = s.pop();
        // console.log(popped); //cc
        // console.log(s.peek()); //bb

        //判断出栈入栈操作合法 
        // 合法出栈顺序加射程一个队列  
        let list_a = [4, 3, 2, 1, 0, 9, 8, 7, 6, 5]
        let list_b = [4, 6, 8, 7, 5, 3, 2, 9, 0, 1]
        let list_c = [2, 5, 6, 7, 4, 8, 9, 3, 1, 0]
        let list_d = [4, 3, 2, 1, 0, 5, 6, 7, 8, 9]
        let list_e = [1, 2, 3, 4, 5, 6, 9, 8, 7, 0]
        let list_f = [0, 4, 6, 5, 3, 8, 1, 7, 2, 9]
        let list_g = [1, 4, 7, 9, 8, 6, 5, 3, 0, 2]
        let list_h = [2, 1, 4, 3, 6, 5, 8, 7, 9, 0]


        function legalExit(list) {
            let temp_stack = new Stack();
            let n = list.length
            for (let i = 0; i < n; i++) {
                temp_stack.push(i)
                while (!temp_stack.empty() && list[0] == temp_stack.peek()) {
                    temp_stack.pop()
                    list.shift()
                }
            }
            if (!temp_stack.empty()) {
                return false
            }
            return true
        }

        console.log('list_a', legalExit(list_a))
        console.log('list_b', legalExit(list_b))
        console.log('list_c', legalExit(list_c))
        console.log('list_d', legalExit(list_d))
        console.log('list_e', legalExit(list_e))
        console.log('list_f', legalExit(list_f))
        console.log('list_g', legalExit(list_g))
        console.log('list_h', legalExit(list_h))

结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值