码迷,mamicode.com
首页 > 其他好文 > 详细

编程离不开生活

时间:2014-08-07 19:04:20      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   java   2014   ar   new   log   

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

 

例子: 反转一个栈

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());
	}
}

编程离不开生活,布布扣,bubuko.com

编程离不开生活

标签:style   blog   color   java   2014   ar   new   log   

原文地址:http://blog.csdn.net/ljhljh8888/article/details/38421691

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!