用lua实现lru,保存最近使用的5个数
欢迎纠错
-- 用lua实现lru,保存最近使用的5个数
-- 实现方法:双向链表
local tLRUCache = {}
-- tLRUCache[nNum1] = { nPre = 0, nNext = nNum2 }
-- tLRUCache[nNum2] = { nPre = nNum1, nNext = nNum3 }
-- tLRUCache[nNum3] = { nPre = nNum2, nNext = nNum4 }
-- tLRUCache[nNum4] = { nPre = nNum3, nNext = nNum5 }
-- tLRUCache[nNum5] = { nPre = nNum4, nNext = 999 }
local nHead = 0 -- 存最老是哪个数(队头)
local nTail = 0 -- 存最新是哪个数(队尾)
-- 取值 更新位置
function Get(nNum)
if not tLRUCache[nNum] then
-- 不存在 返回-1
return -1
end
-- 已存在 更新位置
-- 已经是最后一个数了
local nNext = tLRUCache[nNum]["nNext"]
if nNext >= 999 then
return nNum
end
-- 不是第一个数
local nPre = tLRUCache[nNum]["nPre"]
if nPre > 0 then
tLRUCache[nPre]["nNext"] = nNext
end
tLRUCache[nNext][&#