栈Stack

 

 

local Stack = {}
Stack.__cname = "util.Stack"
Stack.__index = Stack

function Stack.new2(src)
    assert("util.Stack" == src.__cname, "InvalidArgument: not Stack")
    local s = Stack.new()
    s.count = src.count
    for i=1,src.count do
        s.arr[i] = src.arr[i]
    end
    return s
end

function Stack.new()
    local obj = {}
    setmetatable(obj, Stack)
    obj:ctor()
    return obj
end

function Stack:ctor()
    self:_Reset()
end

function Stack:_Reset()
    self.arr = {}
    self.count = 0
end

function Stack:Clear()
    self:_Reset()
end

function Stack:GetCount()
    return self.count
end

function Stack:Push(v)
    self.count = self.count + 1
    self.arr[self.count] = v
end

function Stack:Pop()
    assert(self.count > 0, "out of range")
    local v = self.arr[self.count]
    self.arr[self.count] = nil
    self.count = self.count - 1
    return v
end

function Stack:Peek()
    if self.count > 0 then
        return self.arr[self.count]
    end
    return nil
end

function Stack:Contains(v)
    for i=1,self.count do
        if self.arr[i] == v then
            return true
        end
    end
    return false
end

function Stack:GetIterator()
    self.iteratorCur = self.count
    if nil == self.iterator then
        self.iterator = function(tb, key)
            if self.iteratorCur < 1 then
                return nil
            end
            local ret = self.arr[self.iteratorCur]
            self.iteratorCur = self.iteratorCur - 1
            return ret
        end
    end
    return self.iterator
end

function Stack:__tostring()
    if self.count < 1 then return "" end
    local strTb = {}
    for i=1,self.count do
        local item = self.arr[i]
        table.insert(strTb, tostring(item))
    end
    return table.concat(strTb, ",")
end

return Stack

 

posted @ 2021-11-12 00:28  yanghui01  阅读(17)  评论(0编辑  收藏  举报