Java實現隊列結構的詳細代碼

來源:互聯網
上載者:User

標籤:

一、什麼是隊列結構

一種線性結構,具有特殊的運演算法則【只能在一端(隊頭)刪除,在另一端(隊尾)插入】。

分類:

  1. 順序隊列結構
  2. 鏈式隊列結構

基本操作:

  1. 入隊列
  2. 出隊列

二、準備資料

 1 static final int QUEUELEN = 15; 2  3 class DATA{ 4      5     String name; 6     int age; 7 } 8  9 class SQType{10     DATA[] data = new DATA[QUEUELEN];11     int head;12     int tail;   13 }

在類SQType中data為資料元素,head為隊頭序號,tail為隊尾序號,當head為0時隊為空白,當tail為QUEUELEN時表示隊列已滿。

 

三、初始化隊列

在使用隊列前首先要建立個空隊列,即初始化隊列。

  1. 按符號常量QUEUELEN指定的大小申請一片記憶體空間用來儲存對列中的資料。
  2. 設定head=0和tail=0,表示一個空隊列。
 1 SQType SQTypeInit(){ 2     SQType q; 3     if((q=new SQType())!=null){      //申請記憶體 4         q.head = 0; 5         q.tail = 0; 6         return q; 7     } 8     else 9     {10         return null;11     }12 }

四、判斷空隊列

1 int SQTypeIsEmpty(SQType q){2     int temp = 0;3     if(q.head==q.tail)4     {5         temp = 1;6     }7     return temp;8 }

五、判斷滿隊列

1 int SQTypeIsFull(SQType q){2     int temp = 0;3     if(q.tail==QUEUELEN)4         temp = 1;5     return temp;6 }

六、請空隊列

1 void SQTypeClear(SQType q){2     q.head = 0;3     q.tail = 0;4 }

七、釋放空間

1 void SQTypeFree(SQType q){2     3     if(q!=null){4         q = null;5     }6 }

八、入隊列

 1 int InSQType(SQType q,DATA data){ 2     if(SQTypeIsEmpty(q)==1){ 3         System.out.println("隊列已滿,操作失敗!"); 4         return 0; 5     } 6     else 7     { 8         q.data[q.tail++]=data; 9         return 1;10     }11     12 }

九、出隊列

 1 DATA OutSQType(SQType q){ 2     if(SQTypeIsEmpty(q)==1) 3     { 4         System.out.println("隊列為空白"); 5         return null; 6     } 7     else  8     { 9         return q.data[q.head++];10     }11     return null12 }

十、讀取節點

 1 DATA PeekSQType(SQType q){ 2     if(SQTypeIsEmpty(q)==1) 3     { 4         System.out.println("隊列為空白"); 5         return null; 6     } 7     else  8     { 9         return q.data[q.head];10     }11     return null12 }

十一、計算隊列長度

1 int SQTypeLen(SQType q){2     int temp;3     temp = q.tail - q.head;4     return temp;5 }

 

Java實現隊列結構的詳細代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.