編程離不開生活

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.