劍指offer-面試題7:倆個棧實現隊列(java)

來源:互聯網
上載者:User

標籤:

詳細分析請參照C語言版,這裡僅僅給出實現代碼,注釋很詳細,不得不說java各種api用起來真是爽飛了

 1 package com.xsf.SordForOffer; 2  3 import java.util.Stack; 4  5 /** 6  * 劍指offer pro7,倆個鏈表實現一個隊列 7  * @author ELVIS 8  */ 9 class ListQueue{10     //定義倆個棧11     private Stack<String> stack1 = new Stack<String>();12     private Stack<String> stack2 = new Stack<String>();13     14     //進隊列的元素都放在15     public void addin(String s){16         stack1.push(s);17         System.out.println("輸入 "+s);18     }19     //執行隊列輸出時首先檢測stack2中是否存在資料,如果有直接從stack2中彈出即可否則將stack1中的資料出棧到stack2中再從stack2輸出20     public String output() throws Exception{21         //如果stack2為空白將stack1放入stack2中22         if(stack2.empty()){23             //當stack1不為空白時將其值放入到stack2中24             while(!stack1.empty()){25                 stack2.push(stack1.pop());26             }27         }28         if(stack2.empty()){29             throw new Exception("隊列為空白了,不能輸出元素");30             31         }32         return stack2.pop();33     }34 }35 public class Pro7linkQueue {36     public static void main(String[] args) throws Exception {37         ListQueue test=new ListQueue();38         test.addin("x");39         test.addin("s");40         test.addin("f");41         System.out.println("輸出 "+test.output());42         43         44         test.addin("m");45         test.addin("d");46         47         System.out.println("輸出 "+test.output());48     49         50     }51 }

 

劍指offer-面試題7:倆個棧實現隊列(java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.