编程离不开生活

[栈和队列] 编程离不开生活,栈就像袋子,先装的东西在以下,后面装的在上面,当然倒出时,也是上面的先出,以下的后面出,这就是所谓的“先进后出,后进先出”栈的原理。而队列就像过安检一样,先安检的先通过。后安检的后通过,这就是队列的思想——“先进先出。后进后出”。

 

样例: 反转一个栈

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class QuickTestMain {

	/**
	 * @param args
	 * @author: --LJH--2014-8-7下午4:23:31
	 * @return: void
	 */

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Stack items = new Stack();
		items.push("he"); // he is at the bottom of the stack
		items.push("saw");
		items.push("a");
		items.push("racecar");
		reverseStack(items); // now he is at the top

		// print in order pushed:
		while (items.size() > 0)
			System.out.println(items.pop());
	}

	public static void reverseStack(Stack stack) {
		Queue rev = new LinkedList();
		while (stack.size() > 0)
			rev.offer(stack.pop());				
		while (rev.size() > 0)
			stack.push(rev.poll());
	}
}

转载于:https://www.cnblogs.com/bhlsheji/p/5123330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值