lua 实现 Queue 队列与双端队列

2015-8-22 雨辰 Lua

-- 实现队列与双端队列
local Queue = class("Queue")

function Queue:ctor()
    self.first = 0
    self.last = -1
end

function Queue:pushFront(queue, value)
    queue.first = queue.first - 1
    queue[queue.first] = value
end

function Queue:pushBack(queue, value)
    queue.last = queue.last + 1
    queue[queue.last] = value
end

function Queue:popFront(queue)
    local first = queue.first
    if first > queue.last
    then
        return nil
    end

    local value = queue[first]
    queue[first] = nil
    queue.first = first + 1
    return value
end

function Queue:popBack(queue)
    local last = queue.last
    if last < queue.first
    then
        return nil
    end
    local value = queue[last]
    queue[last] = nil
    queue.last = last - 1
    return value
end

function Queue:length()
    return self.last - self.first + 1;
end

return Queue

标签: lua

发表评论:

雨辰 joyimp|@2011-2018 京ICP备16030765号