天天看點

java 隊列知識

隊列其實 所指生活中排隊的現象,去商場購物,付款時需要排隊, 買飯時需要排隊, 好多事情都是需要排隊, 排在第一位的則先處理,結束後, 後面的人都像前移動一位,在開發中也有好多這樣的事情需要處理,如檔案的下載下傳,短信的發送功能, 等這些都是需要隊列方式實作。好了, 廢話不多說, 詳情見下面代碼! 

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; 

    }  

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(""); 

   }