美文网首页
数据结构

数据结构

作者: lczalh | 来源:发表于2018-09-26 20:54 被阅读15次

    用数组实现栈

    class Stack {
        var stack: [AnyObject]
        var isEmpty: Bool { return stack.isEmpty }
        var peek: AnyObject? { return stack.last }
        var count: Int { return stack.count }
        
        init() {
            stack = [AnyObject]()
        }
    
        func push(object: AnyObject) {
            stack.append(object)
        }
    
        func pop() -> AnyObject? {
            if (!isEmpty) {
                return stack.removeLast()
            } else {
                return nil
            }
        }
    }
    
    let stack = Stack()
    
    stack.push(object: "123" as AnyObject)
    stack.push(object: 123 as AnyObject)
    stack.push(object: 43242 as AnyObject)
    
    print(stack.count)
    
    stack.pop()
    stack.peek
    stack.pop()
    stack.peek
    stack.pop()
    stack.peek
    print(stack.count)
    

    相关文章

      网友评论

          本文标题:数据结构

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