美文网首页
Swift - 堆栈实现

Swift - 堆栈实现

作者: ricefun | 来源:发表于2020-01-16 14:57 被阅读0次
/*堆栈,特点:LIFO( last-in first-out order:后进先出)*/
public struct Stack<T> {
    fileprivate var list = Array<T>()
    
    //push
    public mutating func push(_ element:T) {
        list.append(element)
    }
    
    //pop
    public mutating func pop() ->T?{
        return list.popLast()
    }
    
    //peek 查看堆栈的元素实质就是查看栈顶的元素
    public func peek() -> T? {
        return list.last
    }
}

//用于打印
extension Stack: CustomStringConvertible {
    public var description: String {
        let topDivider = "---Stack---\n"
        let bottomDivider = "-----------\n"
        let stackElements = list.reversed()
        var content = ""
        for item in stackElements {
            content += "\(item)\n"
        }
        return topDivider + content + bottomDivider
    }
}

var pStack = Stack<String>()
pStack.push("a")
pStack.push("b")
pStack.push("c")
pStack.push("d")
pStack.push("e")
pStack.push("f")
print(pStack)
print(pStack.peek())
pStack.pop()
print(pStack)

//打印
---Stack---
f
e
d
c
b
a
-----------

Optional("f")
---Stack---
e
d
c
b
a
-----------

参考链接

相关文章

网友评论

      本文标题:Swift - 堆栈实现

      本文链接:https://www.haomeiwen.com/subject/vgvfzctx.html