標籤: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 stubStack items = new Stack();items.push("he"); // he is at the bottom of the stackitems.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());}}