隊列(儲存結構數組)--Java實現

來源:互聯網
上載者:User

標籤:for   color   出隊   logs   鏈表   儲存結構   迴圈   rem   blog   

 1 /*隊列:其實也是一種操作受限的線性表 2  *特點:先進先出 3  *隊尾指標:負責元素的進隊 4  *隊頭指標:負責元素的出隊 5  *注意:普通隊--容易浪費空間,一般隊列使用最多的就是迴圈隊列--指標環繞 6  *隊列的實現方式:數組/鏈表 7  *隊列判空判滿: 8  *1.按照隊列中元素的個數 9  *2.按照隊頭和隊尾指標的關係10  *存在雙端隊列:每端都可以插入和刪除,其變形可以是操作受限的雙端隊列11  *隊列的應用:其實很多現實世界的規則都是按照排隊這種思想12  * */13 public class MyQueue {14     private int items;//隊列元素的個數15     private long[] arr;//儲存數組16     private int front;//隊頭指標17     private int rear;//隊尾指標18     private int maxSize;//數組的長度19     20     public MyQueue(int s) {21         maxSize = s;22         arr = new long[maxSize];23         front = 0;24         rear = -1;25         items = 0;26     }27     28     //進隊--先加在取29     public void insert(long key){30         if(rear == maxSize - 1){31             rear = -1;32         }33         arr[++rear] = key;34         items++;35     }36     37     //出隊--先取在加138     public long remove(){39         long num = arr[front++];40         if(front == maxSize){41             front = 0;42         }43         items--;44         return num;45     }46     47     //擷取隊頭48     public long getFront(){49         return arr[front];50     }51     52     //判空53     public boolean isEmpty(){54         return items == 0;55     }56     57     public boolean isEmpty1(){58         return (rear + 1 == front ||(front + maxSize - 1 == rear));59     }60     61     62     63     //判滿64     public boolean isFull(){65         return rear == maxSize;66     }67     68     public boolean isFull1(){69         return (rear + 2 == front ||(front + maxSize - 2 == rear));70     }71     72     //擷取隊列元素個數73     public int size(){74         return items;75     }76     77     public int size1(){78         if(rear >= front){79             return rear - front + 1;80         }81         else{82             return (maxSize - front) + (rear + 1);83         }84     }85     86     //顯示隊列87     public void displayQueue(){88         for(int i = front;i < rear;i++){89             System.out.print(arr[i] + " ");90         }91         System.out.println();92     }93     94     95 }

 

隊列(儲存結構數組)--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.