利用链表实现栈

2021-02-02  本文已影响0人  梁森的简书

入栈:插入到头节点的下一个节点。 出栈:移除头节点的下一个节点

/// 栈
struct Stack {
    
    private var head = TNode<Any>(item: nil, next: nil)
    private var count = 0
    
    func isEmpty() -> Bool {
        if count == 0 {
            return true
        } else {
            return false
        }
    }
    
    mutating func push(item: Any) {
        let first = head.next
        let newNode = TNode(item: item, next: first)
        head.next = newNode
        count += 1
    }
    
    mutating func pop() -> Any? {
        let first = head.next
        if first == nil {
            return nil
        }
        head.next = first?.next
        count -= 1
        return first?.item
    }
    
    func printStack() {
        var node = head.next
        while node != nil {
            print("\(node?.item)")
            node = node?.next
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读