您的位置:首页 > 编程语言 > Lua

使用lua语言实现循环链表

2013-03-13 09:16 507 查看
List = {}
--[[ 创建链表]]
function List.new()
local t =  {next = nil, prev = nil, value = 0}
t.next = t
t.prev = t
return t;
end

function List.push_front(list, val)
local t = {next = list.next, prev = list, value = val}
list.next.prev = t
list.next = t
end

function List.push_back(list,val)
local t = {next = list, prev = list.prev, value = val}
list.prev.next = t
list.prev = t
end

function List.pop_front(list)
local t = list.next
list.next = t.next
t.next.prev = list
t = nil
end

function List.pop_back(list)
local t = list.prev
list.prev = t.prev
t.prev.next = list
t = nil
end

function List.find(list , val)
local t = list.next
while not (t == list) do
if t.value == val then
return t
end
t = t.next
end
return nil
end

function List.insert(list , val)
List.push_fornt(list, val)
end

--[[  删除元素  ]]
function List.erase(list, val)
local t = List.find(list, val)
if t then
t.next.prev = t.prev
t.prev.next = t.next
t = nil
else
print("元素不存在")
end
end

--[[  输出链表  ]]
function List.dump(list)
local t = list.next
while not (t == list) do
print(t.value)
t = t.next
end
end

--[[  链表反转  ]]
function List.reverse(list)
local t = list.next
local curnode = list
repeat
curnode.next = curnode.prev
curnode.prev = t
curnode = t
t = t.next
until curnode == list
end
--[[  查找最小值  ]]
function List.find_min(beglist, endlist )
local t = beglist
local m = beglist
while not (t == endlist) do
if t.value < m.value then
m = t
end
t = t.next
end
return m
end

--[[  排序  ]]
function  List.sort(list)
local t = list.next
while not (t == list) do
--[[  从剩余节点中查找最小值  ]]
local m = List.find_min(t, list)
--[[  如果找到的是剩余节点的开始节点,则将开始节点后移  ]]
if m == t then
t = t.next
end
List.pop_front(m.prev)
List.push_front(list, m.value)
end
List.reverse(list)
end

b = List.new()
List.push_front(b, 10)
List.push_front(b, 11)
List.push_front(b, 15)
List.dump(b)
List.reverse(b)
List.dump(b)
List.sort(b)
List.dump(b)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: