链表LRU
簡介
鏈表就是鏈?zhǔn)酱鎯?chǔ)數(shù)據(jù)的一種數(shù)據(jù)結(jié)構(gòu)。雙向鏈表每個(gè)數(shù)據(jù)存儲(chǔ)都包含他的前后數(shù)據(jù)節(jié)點(diǎn)的位置信息(索引/指針)。
class DSChain<T>{//使用棧來進(jìn)行廢棄空間回收private DSStack<int> _recycle;//數(shù)據(jù)需要三個(gè)數(shù)據(jù)來存儲(chǔ)內(nèi)容,分別存儲(chǔ)前后節(jié)點(diǎn)索引和數(shù)據(jù)本身private int[] _prev;private T[] _ds;private int[] _next;//鏈表頭尾的索引,跟蹤表尾主要方便LRU使用private int _head;private int _tail;public DSChain(int length){_head = -1;_tail = -1;_prev = new int[length];_ds = new T[length];_next = new int[length];_recycle = new DSStack<int>(length);//將所有可用空間壓入棧,也可改良當(dāng)順序空間耗盡后再讀取棧中記錄的回收空間for (int i = 0; i < length; i++){_recycle.Push(i);}}//搜索數(shù)據(jù),返回所在索引int Search(T data){if (_head == -1) return -1;int index = _head;while (!_ds[index].Equals(data)){index = _next[index];if (index == -1) return -1;}return index;}public bool Insert(T data){int index;if (!_recycle.Pop(out index)) return false;if (_head == -1){_prev[index] = -1;_ds[index] = data;_next[index] = -1;_tail = index;}else{_prev[index] = -1;_ds[index] = data;_next[index] = _head;_prev[_head] = index;}_head = index;return true;}public bool Delete(T data){int index = Search(data);if (index == -1) return false;if (_prev[index] != -1) _next[_prev[index]] = _next[index];else _head = _next[index];if (_next[index] != -1) _prev[_next[index]] = _prev[index];else _tail = _prev[index];_recycle.Push(index);return true;}//LRUpublic bool DeleteLast(){int index = _tail;if (index == -1) return false;_tail = _prev[index];_next[_prev[index]] = -1;_recycle.Push(index);return true;}//LRU訪問方法,讀取數(shù)據(jù)的同時(shí)調(diào)整數(shù)據(jù)在鏈表中位置//鏈表這種數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn)LRU非常方便public bool LRUAccess(T data){int index = Search(data);if (index == -1) return false;if (_head == index) return true;if (_tail == index) _tail = _prev[index];_next[_prev[index]] = _next[index];if (_next[index] != -1) _prev[_next[index]] = _prev[index];_prev[index] = -1;_next[index] = _head;_prev[_head] = index;_head = index;return true;}}轉(zhuǎn)載于:https://www.cnblogs.com/zhang740/p/3785711.html
總結(jié)
- 上一篇: 一、面试题(持续跟新)
- 下一篇: zookeeper源码