面試題9-用兩個棧來實現一個佇列,完成佇列的Push和Pop操作
阿新 • • 發佈:2018-10-31
- 題目
- 用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。
- 思路:
- 一個棧壓入元素,而另一個棧作為緩衝,將棧1的元素出棧後壓入棧2中
- 程式碼
import java.util.Stack; /** *兩個棧實現一個佇列 * @author MSI */ public class Requeue{ Stack<Integer> sk1=new Stack<Integer>(); Stack<Integer> sk2=new Stack<Integer>(); public void push(int val){ sk1.push(val); } public int pop()throws Exception{//將棧1依次出棧,並壓入棧2 if(sk1.isEmpty()&&sk2==null){ throw new Exception("queue is empty"); } while(sk2.isEmpty()){ while(!sk1.isEmpty()){ sk2.push(sk1.pop()); } } return sk2.pop(); } public static void main(String Args[]) throws Exception{ Requeue q1=new Requeue(); q1.push(1); q1.push(2); q1.push(3); while(q1!=null) System.out.println(q1.pop()); } }
- 輸出
-
1 2 3