Lua 几种常用的数据结构实现

一、链表(linked list)

function TestLinked()
    local list = nil
    print("生成链表Begin")
    for i = 10, 1, -1 do
        print("向链表的头部添加:",i)
        list = { next = list ,value = i}
    end
    print("生成链表End")
    
    print("打印链表:")
    local ret = ""
    local l = list
    while l do 
        if l.next then
            ret = ret .. l.value .. "=>"
        else
            ret = ret .. l.value
        end
        l = l.next
    end
    
    print(ret)
end
TestLinked()

在这里插入图片描述

二、队列与双向队列(queue)

---先进先出
function TestQueue()
    local List = {}
    --创建
    function List.new()
        return {first = 0,last = -1}
    end
    
    function List.push(list,value)
        local first = list.first - 1
        list.first = first
        list[first] = value
    end
    
    function List.pop(list)
        local last = list.last
        if list.first > last then
            error("List is empty")
        end
        local value = list[last]
        list[last] = nil
        list.last = last - 1 
        return value
    end

    --测试代码
    local testList = {first = 0,last = -1}

    for i = 1,10 do
        print("进队列:",i)
        List.push(testList,i)
    end
    print("出队列:",List.pop(testList))       
    print("出队列:",List.pop(testList))
end
TestQueue()

在这里插入图片描述

三、栈(stack)

---先进后出
function TestStack()
    local stackMng = {}
    stackMng.__index = stackMng
    
    function stackMng:new()
        local temp = {}
        setmetatable(temp,stackMng)
        return temp
    end
    
    function stackMng:init()
        self.stackList = {}
    end
    
    function stackMng:pop()
        if #self.stackList == 0 then
            return
        end
        return table.remove(self.stackList,#self.stackList)
    end
    
    function stackMng:push()
        table.insert(self.stackList,#self.stackList+1)
    end
    
    --测试代码
    Stack = stackMng:new()
    Stack:init()
    for i=1,10 do
        print("入栈:",i)
        Stack:push()
    end
    print("\n出栈:",Stack:pop())
end

TestStack()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值