用栈结构解决佩慈糖果盒问题(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));
打印: