用栈的方法解决佩慈糖果盒问题

佩慈糖果盒解决的问题是什么?

    你有一盒佩兹糖果,里面按顺序塞满了红色、黄色和白色的糖果,但是你不喜欢某一个颜色的糖果,在只能使用栈的方法上欲将其取出,但是不能改变盒内其他糖果叠放顺序。

1、先根据栈的功能,封装一个栈方法

class Stack {
    constructor(){
        this.item = []; //存储栈元素
    }
    // 向栈中添加元素
    push(ele) {
        this.item.push(ele)
    }
    // 移除栈顶元素
    pop() {
        return this.item.pop()
    }
    // 返回栈顶元素
    peek() {
        return this.item[this.item.length - 1]
    }
    // 判空
    isEmpty() {
        return this.item.length == 0
    }
    // 清空栈
    clear() {
        this.item = []
    }
    // 元素个数
    size() {
        return this.item.length
    }
}

2、解决思路:以不喜欢黄色糖果为例。

        这里我们要使用到另外个盒子box1,用于放入不是黄色的糖果,当遇到栈顶糖果不是黄色糖果时就将其出栈并放入box1,当遇到是黄色糖果时就直接出栈不放入,直到原来装糖果的盒子为空,最后再将存在box1盒子里的糖果依次出栈并放回原来的盒子就实现了。

 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 Box(sweetBox){

            let bufferBox = new Stack();
            //入栈
            while(!sweetBox.isEmpty()){
               if(sweetBox.peek()!="yellow"){
                bufferBox.push(sweetBox.pop())
               } else{
                sweetBox.pop();
               }
            }
            //出栈
            while(!bufferBox.isEmpty()){
                sweetBox.push(bufferBox.pop())
            }
            return sweetBox;
        }
        console.log(Box(sweetBox));

下面这个方法是多添加一个可以传参的功能:

 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 chock(ele, stack) {
            let box1 = new Stack();
            //入栈
            while (stack.size() > 0) {
                if (stack.peek() !== ele) {
                    box1.push(sweetBox.pop())
                 
                } else {
                    sweetBox.pop()
                }
            }
            //出栈
            while (box1.size() > 0) {
                sweetBox.push(box1.pop())
              
            }
         return sweetBox

        }
        console.log(chock("red", sweetBox));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值