lua程序设计第十四章数据结构答案

本文详细解答了Lua程序设计第14章中的练习,包括14.1、14.2和14.3,深入探讨了数据结构的相关应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习14.1

a = {   {nil,nil,1,nil,nil,nil,nil},
        {nil,nil,nil,nil,nil,nil,nil},
        {3,nil,nil,nil,nil,nil,nil},
        {nil,nil,nil,5,nil,nil,nil},
        {nil,nil,nil,nil,nil,nil,nil},
        {nil,nil,nil,nil,nil,7,4}
	}

b = {
        {nil,nil,10,nil,nil,nil,nil},
        {nil,nil,nil,20,nil,nil,nil},
        {nil,nil,nil,nil,nil,nil,nil},
        {nil,nil,nil,50,nil,nil,nil},
        {nil,nil,20,nil,nil,nil,nil},
        {nil,nil,nil,10,nil,nil,4}
    }

function add(a, b)

	local c = {}
	for i = 1, #a do
		local resultline = {}
		for k,va in pairs(a[i]) do
			for k, vb in pairs(b[i])do
				local res = (resultline[k] or 0) + va + vb
				resultline[k] = (res ~= 0) and res or nil
			end
		end
		c[i] = resultline
	end
	return c
end

c = add(a,b)
print(c[4][4])

练习14.2

function listnew()
	return {first = 0, last = -1}
end

function pushFirst(list, value)
	local first = list.first - 1
	list.first = first
	list[first] = value
end

function pushLast(list, value)
	local last = list.last + 1
	list.last = last
	list[last] = value
end

function popFirst(list)
	local first = list.first
	if first > list.last then
	print("list is empty")
		return 0
	end
	local value = list[first]
	list[first] = nil
	list.first = first + 1
	return value
end

function popLast(list)
	local last = list.last
	if list.first > last then
	print("list is empty")
			return 0
	end
	local value = list[last]
	list[last] = nil
	list.last = last - 1
	return value
end

a = listnew()
print(popFirst(a))

练习14.3

 function name2node(graph,name)
	local node = graph[name]
	if not node then
		node = {name = name,adj = {}}
		graph[name] = node
	end
	return node
end

function readgraph(filename)
	local graph = {}
	for line in io.lines(filename) do
		local namefrom,nameto,Label = string.match(line,"(%S+)%s+(%S+)%s+(%d+)")
		local from = name2node(graph,namefrom)
		local to = name2node(graph,nameto)
		temp = {[1] = true,[2] = Label}
		from.adj[to] = temp
	end
return graph
end

t =  readgraph("test.txt")
node = name2node(t,"a")
node2 = name2node(t,"b")
print(node.adj[node2][1])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值