剑指offer-面试题7:俩个栈实现队列(java)

时间:2023-03-09 01:41:33
剑指offer-面试题7:俩个栈实现队列(java)

详细分析请参照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 }