1. 程式人生 > >判斷儲存,是棧?還是佇列?

判斷儲存,是棧?還是佇列?

  判斷一段 輸入-輸出 模式,是利用了棧還是佇列的一個方法

 1 import java.util.*;
 2 
 3 public class Stack_Queue {
 4         static Scanner sc = new Scanner(System.in);
 5         
 6         public static boolean isQueue(int a[], int n){
 7             Queue<Integer> p = new LinkedList<Integer>();
 8             int
t = 1; 9 for(int i = 0; i < n; i++){ 10 while(t <= n || (!p.isEmpty() && p.peek() <= n)){ 11 // System.out.println("p.peek="+p.peek()+",t="+t+",a="+a[i]); 12 if(!p.isEmpty() && p.peek() == a[i]){ 13 // System.out.println("p="+p.peek()+"->out");
14 p.poll(); 15 break; 16 } 17 else if(t == a[i]){ 18 // System.out.println(t+"->out"); 19 t++; 20 break; 21 } 22
// System.out.println("noout,"+t+"->p"); 23 p.add(t++); 24 if(t > n+1) 25 break; 26 } 27 } 28 return p.isEmpty(); 29 } 30 public static boolean isStack(int a[], int n){ 31 Stack<Integer> s = new Stack<Integer>(); 32 int k = 1; 33 for(int i = 0; i < n; i++){ 34 while((s.isEmpty() || s.peek() != a[i]) && k <= n){ 35 s.push(k++); 36 // System.out.print("s.peek="+s.peek()+","); 37 } 38 if(!s.isEmpty() && s.peek() == a[i]) 39 s.pop(); 40 } 41 return s.isEmpty(); 42 } 43 44 public static void Stack_Or_Queue(String[] args) { 45 int id = 1; 46 while(sc.hasNext()){ 47 while(sc.hasNext()){ 48 int n = sc.nextInt(); 49 if(n == 0) break; 50 Queue<Integer> p = new LinkedList<Integer>(); 51 Stack<Integer> s = new Stack<Integer>(); 52 int[] a = new int[n]; 53 for(int i = 0; i < n; i++) 54 a[i] = sc.nextInt(); 55 56 for(int i = 0; i < n; i++){ 57 if(i != n-1) 58 System.out.print(a[i] + " "); 59 else 60 System.out.print(a[i] + ":"); 61 } 62 if(isStack(a, n) && isQueue(a, n)) 63 System.out.println("both"); 64 else if(isStack(a, n)) 65 System.out.println("stack"); 66 else if(isQueue(a, n)) 67 System.out.println("queue"); 68 else 69 System.out.println("neither"); 70 } 71 72 } 73 74 System.gc();sc.close(); 75 } 76 }