数据结构--链表--LRU缓存
生活随笔
收集整理的這篇文章主要介紹了
数据结构--链表--LRU缓存
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
LRU(Least Recently Used)緩存策略:
通俗的講就是,最近使用的放在最前面,不經常使用的放后面,滿了就刪除
C++代碼實現
//用單鏈表實現LRU策略 2019.3.17 #include <iostream> #include <string> using namespace std; struct weburl {string website;weburl *next;}; class webList {weburl *p_head;size_t cacheSize; public:webList():p_head(new weburl),cacheSize(0){p_head->next = NULL; //犯錯,開始沒有寫這句,導致后面有的地方非法訪問}~webList(){eraseAll();delete p_head;}void eraseAll(){weburl *tempNode = p_head->next, *del_Node = NULL;while(tempNode != NULL){del_Node = tempNode;tempNode = tempNode->next;delete del_Node;cacheSize--; // tempNode = tempNode->next; //千萬注意順序,之前放這錯了!!!}}weburl* get_head(){return p_head;}weburl* find(string &str){weburl *tempNode = p_head;while(tempNode->next != NULL){if(tempNode->next->website == str)return tempNode; //返回的是找到的節點的上一個節點elsetempNode = tempNode->next;}return NULL;}size_t getCacheSize(){return cacheSize;}void incrCacheSize(){cacheSize++;}void decrCacheSize(){cacheSize--;}void push_front(weburl *p){p->next = p_head->next;p_head->next = p;incrCacheSize();}void move_to_front(weburl *p){p->next = p_head->next;p_head->next = p;}void pop_back(){weburl *p = p_head, *prev = NULL;while(p->next != NULL){prev = p;p = p->next;}prev->next = NULL;delete p;decrCacheSize();}void printCacheList(){cout << "the recently visit website: " << endl;weburl *tempNode = p_head;size_t i = 0;while(tempNode->next != NULL){tempNode = tempNode->next;cout << ++i << " " << tempNode->website << endl;}} }; int main() {char conti = 'y';size_t maxCacheSize = 5;string web;webList cacheList;while(conti == 'y' || conti == 'Y'){cout << "-------------------------------------------" << endl;cout << "please enter the weburl you want to visit: " << endl;cin >> web;weburl *tempNode = cacheList.find(web);weburl *head = cacheList.get_head();if (tempNode == NULL) //沒有找到,是新的訪問記錄{weburl *newWeb = new weburl;newWeb->website = web;newWeb->next = NULL;if (cacheList.getCacheSize() < maxCacheSize) //存儲沒滿,直接加到隊首{cacheList.push_front(newWeb);} else //存儲滿了,刪除隊尾,插入新的到隊首{cacheList.pop_back();cacheList.push_front(newWeb);}} else //從已有的數據中找到了記錄{if (tempNode == head) ; //記錄在第一條,則無需操作else {weburl *mvRecord = tempNode->next;tempNode->next = mvRecord->next; //把該記錄從鏈表中斷開cacheList.move_to_front(mvRecord); //把該記錄移到隊首}}cacheList.printCacheList();cout << "continue? y/n" << endl;cin >> conti;cin.get();}return 0; }Valgrind檢查結果
總結
以上是生活随笔為你收集整理的数据结构--链表--LRU缓存的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 动态规划应用--找零钱
- 下一篇: POJ 2255 Tree Recove