LRU隊列的實現

來源:互聯網
上載者:User

標籤:

package Queue;public class LRUQueue<T> {private T[] queue = null;private int num; //隊列中元素的個數/** * 指定大小構造隊列 * @param capacity */public LRUQueue(int capacity) {this.num = 0;queue = (T[]) new Object[capacity];}/** * 判斷隊列是為空白 */public boolean isEmpty() {return num==0? true:false;}/** * 判斷隊列是否已滿 */public boolean isFull() {return num==queue.length? true:false;}/** * 尋找某值在隊列中的索引,沒有則返回-1 */public int searchIndex(T value) {for(int i=0; i<num; i++) {if(queue[i]==value)return i;}return -1;}/** * 進隊列 */public void push(T value) {int Vindex = this.searchIndex(value);//隊列中沒有valueif(Vindex==-1) {//判斷隊列是否滿boolean isfull = this.isFull();if(isfull==false) {queue[num++] = value;}//滿else {this.pop();queue[num++] = value;}}//隊列中有valueelse {T temp = queue[Vindex];for(int i=Vindex; i<num; i++) {queue[i] = queue[i+1];}queue[num-1] = value;}}/** * 出隊列 * @param args */public T pop() {T popValue = queue[0];for(int i=0; i<num; i++) {queue[i] = queue[i+1];}queue[num--] = null;return popValue;}/** * 列印佇列資訊 * @param args */public void print() {for(int i=0; i<this.num; i++) {System.out.print(queue[i] + " ");}System.out.println();}public static void main(String[] args) {LRUQueue<Integer> lru_q = new LRUQueue<Integer>(5);lru_q.push(5);lru_q.print();lru_q.push(3);lru_q.print();lru_q.push(5);lru_q.print();lru_q.push(4);lru_q.print();lru_q.push(3);lru_q.print();}}

LRU是Least Recently Used 近期最少使用演算法。
  LRU隊列即把隊列中最近最少使用的資料淘汰掉。

LRU隊列的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.