標籤:
詳細分析請參照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)