隊列的應用很普遍。如操做系統中各類數據緩衝區的先進先出管理,應用系統中各類服務請求的排隊管理等。java
如下例子是用一個隊列和堆棧實現判斷一個字符序列是不是迴文。算法
【例子】編寫判斷一個字符序列是不是迴文的函數。迴文是指一個字符序列以中間字符爲基準兩邊字符徹底相同,如字符序列"ABCDEDCBA"就是迴文,而字符序列"ABCDEDBAC"就不是迴文。設計一個主函數進行測試。數組
【算法思想】設字符數組str中存放了要判斷的字符串。把字符數組中的字符逐個分別存入一個隊列和一個堆棧,而後逐個出隊列和退棧並比較出隊列的字符是否相等,若所有相等則該字符序列是迴文,不然反之。app
【源代碼】ide
Queue.java函數
1 package seqqueue; 2 3 public interface Queue { 4 //把元素obj插入隊尾 5 public void append(Object obj)throws Exception; 6 //把對頭數據元素刪除並由函數返回 7 public Object delete()throws Exception; 8 //取對頭數據元素並返回 9 public Object getFront()throws Exception; 10 //非空否。 11 public boolean notEmpty(); 12 }
SeqQueue.java測試
1 package seqqueue; 2 3 4 public class SeqQueue implements Queue{ 5 static final int defaultSize = 10; 6 int front; 7 int rear; 8 int count; 9 int maxSize; 10 Object[] data; 11 12 public SeqQueue(){ 13 initiate(defaultSize); 14 } 15 16 public SeqQueue(int sz){ 17 initiate(sz); 18 } 19 private void initiate(int sz) { 20 // TODO Auto-generated method stub 21 maxSize = sz; 22 front=rear = 0; 23 count = 0; 24 data = new Object[sz]; 25 } 26 27 @Override 28 public void append(Object obj) throws Exception { 29 // TODO Auto-generated method stub 30 if(count > 0 && front == rear) 31 throw new Exception("隊列已滿!"); 32 data[rear]=obj; 33 rear=(rear+1)%maxSize; 34 count++; 35 } 36 37 @Override 38 public Object delete() throws Exception { 39 // TODO Auto-generated method stub 40 if(count == 0) 41 throw new Exception("隊列已空!"); 42 Object temp = data[front]; 43 front=(front+1)%maxSize; 44 count--; 45 return temp; 46 } 47 48 @Override 49 public Object getFront() throws Exception { 50 // TODO Auto-generated method stub 51 if(count == 0) 52 throw new Exception("隊列已空!"); 53 return data[front]; 54 } 55 56 @Override 57 public boolean notEmpty() { 58 // TODO Auto-generated method stub 59 return count !=0 ; 60 } 61 62 }
SeqQueueTest.javaui
1 package seqqueue; 2 3 import seqstack.SeqStack; 4 5 public class SeqQueueTest { 6 public static void huiWei(String str) throws Exception{ 7 int n=str.length(); 8 SeqStack myStack=new SeqStack(n); 9 SeqQueue myQueue=new SeqQueue(n); 10 11 for(int i = 0 ; i < n; i++) 12 { 13 myQueue.append(str.substring(i, i+1)); 14 myStack.push(str.substring(i, i+1)); 15 } 16 17 while(myQueue.notEmpty() && myStack.notEmpty()) 18 { 19 if(!myQueue.delete().equals(myStack.pop())) 20 { 21 System.out.println(str+"不是迴文!"); 22 return; 23 } 24 } 25 System.out.println(str+"是迴文!"); 26 } 27 28 public static void main(String args[]) 29 { 30 String str1="ABCDEDCBA"; 31 String str2="ABCDEDBAC"; 32 String str3="ABCDDCBA"; 33 try 34 { 35 huiWei(str1); 36 huiWei(str2); 37 huiWei(str3); 38 }catch(Exception e) 39 { 40 System.out.println(e); 41 42 } 43 44 } 45 46 }
【運行截圖】spa