佩慈糖果盒解决的问题是什么?
你有一盒佩兹糖果,里面按顺序塞满了红色、黄色和白色的糖果,但是你不喜欢某一个颜色的糖果,在只能使用栈的方法上欲将其取出,但是不能改变盒内其他糖果叠放顺序。
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));