java 隊列

先進先出

1、先寫個隊列類

package com.zg; 

class Queue   //隊列類 
    { 
    private int maxSize; //隊列長度,由構造函數初始化 
    private long[] queArray; // 隊列 
    private int front; //隊頭 
    private int rear; //隊尾 
    private int nItems;  //元素的個數 
//-------------------------------------------------------------- 
    public Queue(int s)           // 構造函數 
       { 
       maxSize = s; 
       queArray = new long[maxSize]; 
       front = 0; 
       rear = -1; 
       nItems = 0; 
       } 
//-------------------------------------------------------------- 
    public void insert(long j)    // 進隊列 
       { 
       if(rear == maxSize-1)          // 處理循環 
          rear = -1; 
       queArray[++rear] = j;          // 隊尾指針加1,把值j加入隊尾 
       nItems++;                    
       } 
//-------------------------------------------------------------- 
    public long remove()          // 取得隊列的隊頭元素。 
       { 
       long temp = queArray[front++]; // 取值和修改隊頭指針 
       if(front == maxSize)            // 處理循環 
          front = 0; 
       nItems--;                      
       return temp; 
       } 
//-------------------------------------------------------------- 
    public long peekFront()       // 取得隊列的隊頭元素。該運算與 remove()不同,後者要修改隊頭元素指針。 
       { 
       return queArray[front]; 
       } 
//-------------------------------------------------------------- 
    public boolean isEmpty()     // 判隊列是否爲空。若爲空返回一個真值,否則返回一個假值。 
       { 
       return (nItems==0); 
       } 
//-------------------------------------------------------------- 
    public boolean isFull()      // 判隊列是否已滿。若已滿返回一個真值,否則返回一個假值。 
       { 
       return (nItems==maxSize); 
       } 
//-------------------------------------------------------------- 
    public int size()            // 返回隊列的長度 
       { 
       return nItems; 
       } 
//-------------------------------------------------------------- 
    }  

 

 

2、調用一下這個隊列

package com.zg;

public class IntegerQueue { 
	public static void main(String[] args) 
	   { 
	Queue theQueue = new Queue(5);   // 隊列有5個元素 
	
	   theQueue.insert(10);             // 添加4個元素 
	   theQueue.insert(20); 
	   theQueue.insert(30); 
	   theQueue.insert(40); 
	
	   theQueue.remove();               // 移除3個元素 
	   theQueue.remove();               // (10, 20, 30) 
	   theQueue.remove(); 
	
	   theQueue.insert(50);             // 添加4個元素 
	   theQueue.insert(60);           
	   theQueue.insert(70); 
	   theQueue.insert(80); 
	   
	
	   while( !theQueue.isEmpty() )     // 遍歷隊列並移除所有元素 
	      {                            
	      long n = theQueue.remove();   // (40, 50, 60, 70, 80) 
	      System.out.print(n); 
	      System.out.print(" "); 
	      } 
	   System.out.println(""); 
	   }  
} 

 

發佈了141 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章