第四章栈(3)

3.现实生活中栈的一个例子是佩兹糖果盒。想象一下你有一盒佩兹糖果,里面塞满了红色、黄色和白色的糖果,
但是你不喜欢黄色的糖果。使用栈(有可能用到多个栈)写一段程序,在不改变盒内其他糖果叠放顺序的基础上,

将黄色糖果移出。

let candyBox=new Stack();
candyBox.push('red');
candyBox.push('yellow');
candyBox.push('red');
candyBox.push('yellow');
candyBox.push('white');
candyBox.push('yellow');
candyBox.push('white');
candyBox.push('yellow');
candyBox.push('white');
candyBox.push('red');

function getCandy(ele,stack)
{
	let getCandyStack=new Stack();
	let tmpCandyStack=new Stack();

	while(!stack.isEmpty())
	{
		if(stack.peek()==ele.trim())
		{
			getCandyStack.push(ele);
			stack.pop();
		}else
		{
			tmpCandyStack.push(stack.pop());
		}
	}
	while(!tmpCandyStack.isEmpty())
	{
		stack.push(tmpCandyStack.pop());
	}
}

getCandy('yellow',candyBox);
console.log("移出后:");
while(!candyBox.isEmpty())
{
	
	console.log(candyBox.pop());
}

猜你喜欢

转载自blog.csdn.net/qq_16829085/article/details/80892494