使用lua语言实现循环链表

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值