话不多说上代码:
1,时间复杂度:查询, 删除,增加,修改 O(1)
2,支持 for 循环有序遍历
设计思路:
一个普通字典 + 一个双向链表
普通字典: key + node({preNode, nextNode, key, value})
遍历时:firstNode 到 lastNode
-- 有序字典
local OrderDictionary2 = {}
OrderDictionary2.__index = OrderDictionary2
function OrderDictionary2:New()
local baseTable = {
count = 0,
firstNode = nil, -- 头结点
lastNode = nil, -- 尾结点
dic_kye_node = {}, -- key : 对应的节点
}
return setmetatable(baseTable, self)
end
setmetatable(OrderDictionary2, { __call = OrderDictionary2.New})
function IterOrderDic2(oderDic, curNode)
if curNode then
return curNode.next, curNode.k, curNode.v
end
end
function PairsOrderDic2(oderDic)
if not oderDic then
error("oderDic is nil")
end
return IterOrderDic2, oderDic, oderDic.firstNode
end
function OrderDictionary2:index(table_key)
local v = self.table_key
if v then
return v
end
v = self.dic_kye_node[table_key]
if v then
return v.v
end
return nil
end
function OrderDictionary2:remove(key)
local node = self.dic_kye_node[key]
if node then
-- 修改链表的链接,当前节点的上一个节点指向当前节点的下一个节点
node.pre.next = node.next
self.dic_kye_node[key] = nil
self.count = self.count - 1
end
end
function OrderDictionary2:getValue(key)
local node = self.dic_kye_node[key]
if node then
return node.v
end
return nil
end
function OrderDictionary2:add(key, value)
local node = self.dic_kye_node[key]
-- 已有修改操作
if node then
node.v = value
return
end
-- 无 新增
node = {pre = false, next = false, k = key, v = value}
self.dic_kye_node[key] = node
-- 链表记录
if self.lastNode then
self.lastNode.next = node
node.pre = self.lastNode
self.lastNode = node
else
-- 无尾结点,必然无头结点
self.lastNode = node
self.firstNode = node
end
self.count = self.count + 1
end
function OrderDictionary2:clear()
self.count = 0
self.dic_kye_node = {} -- key : 对应的节点
self.firstNode = nil -- 头结点
self.lastNode = nil -- 尾结点
end
return OrderDictionary2
测试逻辑:
-- 有序字典测试第一个
local table1 = OrderDictionary2()
local str = ""
table1:add("key1", "value1")
table1:add("key2", "value2")
table1:add("key3", "value3")
table1:add("key4", "value4")
table1:add("key5", "value5")
table1:add("key6", "value6")
table1:add("key7", "value7")
table1:add("key8", "value8")
table1:add("key6", 10) -- replace test
table1:remove("key5") -- remove test
--table1:clear() -- clear test ok
table1:add("key5", "value5")
table1:add("key9", "value9")
for i, k, v in PairsOrderDic2(table1) do
str = str .. string.format(" %s : %s : %s : count = %s \n", i, k, v, table1.count)
end
-- 有序字典测试第二个
local table2 = OrderDictionary2()
table2:add("key4", "value4")
table2:add("key5", "value5")
table2:add("key6", "value6")
table2:add("key7", "value7")
table2:add("key8", "value8")
table2:add("key6", 10) -- replace test
table2:remove("key5") -- remove test
table2:add("key5", "value5")
table2:add("key9", "value9")
for i, k, v in PairsOrderDic2(table2) do
-- i type is table
-- when last i type is false
str = str .. string.format(" %s : %s : %s : count = %s \n", i, k, v, table2.count)
end
print(str)