csdn學習筆記二:連結串列原型、do原型分析
阿新 • • 發佈:2018-11-09
設計連結串列,並設計其迭代函式
生成連結串列、列印連結串列
arr = {10, 20, 30, 100, 101, 88, 50}; head = nil; local i = 1 while true do if arr[i] then head = {value = arr[i], next = head}; ---從右往左執行的 --[[ head表實際儲存的資料是這樣的 {value = 50, next = {value = 88 ,next = { value = 101 , next = {value = 100 ,next = nil}}}} ]] i = i + 1; else break; end end while head do print(head.value); head = head.next; end ---------------------------------------- output: 50 88 101 100 30 20 10
用無狀態迭代器來實現
function iterator(head,next) if next == nil then return head; else return next.next; end end function traverse(head) return iterator,head,nil; --實際是給_f(_s,_v)呼叫的 end for v in traverse(head) do print(v.value); end --------------------------------------- output: 50 88 101 100 30 20 10
用有狀態迭代器來實現
function iterator(head) local next = nil; return function () if next == nil then next = head; return next; else next = next.next; return next; end end end for k,v in iterator(head) do print(k.value); end ---------------------------------------- output: 50 88 101 100 30 20 10
for原型分析
arr = {10, 20, 30, 100, 101, 88, 50};
head = nil;
local i = 1
while true do
if arr[i] then
head = {value = arr[i], next = head}; ---從右往左執行的
--[[
head表實際儲存的資料是這樣的
{value = 50, next = {value = 88 ,next = { value = 101 , next = {value = 100 ,next = nil}}}}
]]
i = i + 1;
else
break;
end
end
function iterator(head)
local next = nil;
return function ()
if next == nil then
next = head;
return next;
else
next = next.next;
return next;
end
end
end
do
local _f, _s, _v = iterator(head);
--[[
local _f, _s, _v = iterator(head);
引用iterator(head)函式,第一次返回_f, _s和_v都是nil,_f實際就是iterator裡面返回的函式,
next初始化等於nil,nil相當於一個static變數,會一直在這個迴圈結束前儲存變化next的變數,
]]
while true do
local k,v = _f(_s,_v); ----iterator(head,nil) 2: iterator(nil, head)
--[[
local k,v = _f(_s,_v);
_f呼叫的時候傳遞的兩個引數是nil,nil,第一次執行next=nil,返回head,把next賦值head
第二次執行的時候next=head,返回了next.next,等價於head.next,
]]
_v = k; ----- _v = head;
--[[
_v = k;
把返回的值賦值給_v,再次帶入迴圈
]]
if k == nil then break; end
print(k.value);
end
end
--------------------------------------------------------
output:
50
88
101
100
30
20
10