記憶體淘汰機制:
實現乙個單鏈表,包括增刪查改的方法。
新資料插入到鍊錶頭部/**
* @auther: allen
* @date: 2019/8/22 14:40
* @description: 單鏈表
*/public class linkedlist
class node
}//增加
/*** 向鍊錶頭部新增元素
* @param data
*/protected void put(t data)
/*** 向鍊錶指定下標新增元素
* @param index
* @param data
*/protected void put(int index, t data)
node previous = head;
node cur = head;
for (int i = 0; i < index; i++)
node node = new node( data, cur);
previous.next = node;
size++;
}/**
* 檢查下標是否越界
* @param index
*/protected void checkpointindex(int index)
}//刪除
/*** 移除鍊錶頭部元素
* @return
*/protected t remove()
return null;
}/**
* 移除鍊錶指定下標元素
* @param index
* @return
*/protected t remove(int index)
pervious.next = cur.next;
cur.next = null; //help gc
size--;
return cur.data;
}/**
* 移除鍊錶最後乙個元素
* @return
*/protected t removelast()
cur.next = null;
size --;
return cur.data;
}return null;
}//修改
/*** 修改鍊錶指定下標元素
* @param index
* @param data
*/protected void set(int index, t data) throws exception
node cur = head;
for (int i = 0; i < index; i++)
cur.data = data;
}//查詢
/*** 獲取鍊錶頭部元素
* @return
*/protected t get()else
}/**
* 獲取鍊錶指定下標元素
* @param index
* @return
*/protected t get(int index) throws exception
node cur = head;
for (int i = 0; i < index; i++)
return cur.data;
}@override
public string tostring()
system.out.println();
return super.tostring();
}public static void main(string args) throws exception
list.tostring();
//list.put(0,11);
list.tostring();
//try catch (exception e)
}}
當快取命中(即快取資料被訪問),資料要移到表頭
當鍊表滿的時候,將鍊錶尾部的資料丟棄
繼承單鏈表,實現例如lru演算法。
/**
* @auther: allen
* @date: 2019/8/22 17:38
* @description: 用單鏈表實現lru快取演算法
*/public class lrulinkedlistextends linkedlistelse
}/**
** @return
*/public t lruremove()
/*** lruget方法
* @return
*/public t lruget(int index)
node pervious = head;
node cur = head;
for (int i = 0; i < index; i++)
//儲存返回結果
t result = cur.data;
//把當前節點移到頭節點
//移除當前節點
pervious.next = cur.next;
//把當前節點移到表頭
cur.next = head;
//儲存頭節點資訊
head = cur;
return result;
}public static void main(string args)
lrulist.tostring();
lrulist.lruget(3);
lrulist.tostring();
}public lrulinkedlist()
public lrulinkedlist(int memory_size)
}
雙鏈表實現LRU
題目 lru 快取機制 設計和實現乙個 lru 最近最少使用 快取資料結構,使它應該支援一下操作 get 和 put。get key 如果 key 存在於快取中,則獲取 key 的 value 總是正數 否則返回 1。put key,value 如果 key 不存在,請設定或插入 value。當快取...
LRU演算法實現
jdk 中的實現 在jdk 中linkedhashmap 可以作為lru 演算法以及插入順序的實現,linkedhashmap 繼承自hashmap 底層結合hash 表和雙向鍊錶,元素的插入和查詢等操作通過計算hash 值找到其陣列位置,在做插入或則查詢操作是,將元素插入到鍊錶的表頭 當然得先刪除...
單鏈表之C 實現
在實現單鏈表時要注意對單鏈表的邏輯儲存 物理儲存有清晰的概念。如上圖鍊錶已經完成,其邏輯結構如上。當需要對其進行操作,比如插入 刪除,通常需要引 入 指標,如上的ptr1 ptr2。在程式設計時一定要注意通過ptr1 ptr2對鍊錶結構的操作是正確的。而 不僅僅是你覺得正確的。下面給大家看下我的單鏈...