用栈结构解决佩慈糖果盒问题(JavaScript)

封装的栈操作方法:

https://www.cnblogs.com/LIXI-/p/16612874.html

 

        var sweetBox = new Stack();
        sweetBox.push('red');
        sweetBox.push('yellow');
        sweetBox.push('red');
        sweetBox.push('yellow');
        sweetBox.push('white');
        sweetBox.push('yellow');
        sweetBox.push('white');
        sweetBox.push('yellow');
        sweetBox.push('white');
        sweetBox.push('red');

         function CandyBox(sweetBox){
            // 创建一个放不是黄色盒子的栈
            let BufferBox = new Stack();
            // 当糖果盒不为空时,
            while(!sweetBox.isEmpty()){
                if(stack.peek() !="yellow"){
                    BufferBox.push(sweetBox.pop())
                }else{
                    sweetBox.pop()
                }
            }

            while(!BufferBox.isEmpty()){
                sweetBox.push(BufferBox.pop())
            }
            return sweetBox
        }

        console.log(CandyBox(sweetBox));    

打印:

 

posted on 2022-08-23 10:00  香香鲲  阅读(18)  评论(0编辑  收藏  举报