使用lua語言實現迴圈鏈表

來源:互聯網
上載者:User
List = {}--[[ 建立鏈表]]function List.new()local t =  {next = nil, prev = nil, value = 0}t.next = tt.prev = treturn t;endfunction List.push_front(list, val)local t = {next = list.next, prev = list, value = val}list.next.prev = tlist.next = tendfunction List.push_back(list,val)local t = {next = list, prev = list.prev, value = val}list.prev.next = tlist.prev = tendfunction List.pop_front(list)local t = list.nextlist.next = t.nextt.next.prev = listt = nilendfunction List.pop_back(list)local t = list.prevlist.prev = t.prevt.prev.next = listt = nilendfunction List.find(list , val)local t = list.nextwhile not (t == list) doif t.value == val thenreturn tendt = t.nextendreturn nilendfunction List.insert(list , val)List.push_fornt(list, val)end--[[  刪除元素  ]]function List.erase(list, val)local t = List.find(list, val)if t thent.next.prev = t.prevt.prev.next = t.nextt = nilelseprint("元素不存在")endend--[[  輸出鏈表  ]]function List.dump(list)local t = list.nextwhile not (t == list) doprint(t.value)t = t.nextendend--[[  鏈表反轉  ]]function List.reverse(list)local t = list.nextlocal curnode = listrepeat curnode.next = curnode.prevcurnode.prev = tcurnode = tt = t.nextuntil curnode == list end--[[  尋找最小值  ]]function List.find_min(beglist, endlist )local t = beglistlocal m = beglistwhile not (t == endlist) doif t.value < m.value thenm = tendt = t.nextendreturn mend--[[  排序  ]]function  List.sort(list)local t = list.nextwhile not (t == list) do--[[  從剩餘節點中尋找最小值  ]]local m = List.find_min(t, list)--[[  如果找到的是剩餘節點的開始節點,則將開始節點後移  ]]if m == t thent = t.nextendList.pop_front(m.prev)List.push_front(list, m.value)endList.reverse(list)endb = 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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.