1. 程式人生 > >005 兩個棧組成隊列

005 兩個棧組成隊列

可能 public sys inf 操作 方法 main import 第一個

一:主題

1.題目

  用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。

2.程序思路

  從隊列與棧的特點上進行寫程序。

  首先,棧的特點是先進後出,而隊列是先進先出。

  所以,要實現隊列,需要使用兩個棧進行組合。

  做法,我以為,讓第一個作為push的棧,然後,pop的時候,將第一個棧中的數據都轉移到棧2,然後把最上面的彈出來。

  註意點:可能一次性push多個數據,所以,在pop的時候,再去清空棧1。  

3.程序

 1 package first;
 2 
 3 import com.sun.org.apache.bcel.internal.generic.PUSH;
4 import sun.awt.windows.ThemeReader; 5 6 import javax.xml.soap.Node; 7 import java.util.Stack; 8 9 public class StackWithTwoQueues { 10 //作為入棧 11 private static Stack<Integer> stack1=new Stack<Integer>(); 12 //作為出棧 13 private static Stack<Integer> stack2=new Stack<Integer>();
14 15 /** 16 * 測試 17 * @param args 18 */ 19 public static void main(String[] args) { 20 push(1); 21 push(2); 22 push(5); 23 int val=pop(); 24 System.out.println(val); 25 push(1); 26 int val2=pop(); 27 System.out.println(val2);
28 29 } 30 /** 31 * 實現push方法 32 */ 33 34 public static void push(int val){ 35 stack1.push(val); 36 } 37 38 /** 39 * 實現pop方法 40 * @return 41 */ 42 public static int pop(){ 43 //將數據都放到2中 44 while (!stack1.isEmpty()){ 45 stack2.push(stack1.pop()); 46 } 47 if(!stack2.isEmpty()){ 48 int node=stack2.pop(); 49 return node; 50 }else { 51 throw new RuntimeException("null"); 52 } 53 } 54 }

4.現象

  技術分享圖片

005 兩個棧組成隊列