Swift中的栈和队列

2016-07-31  本文已影响6人  Isy
//栈是后进先出的结构
//栈结构的类
//支持push,pop,isEmpty,peek,size
class Stack {
    var stack: [AnyoBject]
    
    init() {
        stack = [AnyoBject]()
    }

    func push(object: AnyObject) -> Bool {
        return stack.append(object)
    }

    func pop() -> AnyObject? {
        if !isEmpty() {
            return stack.removeLast()
        } else {
            return nil
        }
    }

    func isEmpty() -> Bool {
        return stack.isEmpty
    }

    func peek() -> AnyObject? {
        return stack.last
    }

    func size() -> Int {
        return stack.count
    }
}

//队列是先进先出的类
//应用GCD,NSOperationQueue
//enqueue,dequeue,isEmpty,peek,size
class Queue {
    var queue: [AnyObject]
    
    init() {
        queue = [AnyObject]()
    }

    func enqueue(object: AnyObject) -> Bool {
        return queue.append(object)
    }
    
    func dequeue() -> AnyObject? {
        if !isEmpty() {
            return queue.removeFirst()
        } else {
            return nil

        }
    }
    
    func isEmpty() -> Bool {
        return queue.isEmpty
    }
    
    func peek() -> AnyObject? {
        return queue.first
    }

    func size() -> Int {
        return queue.count
    }

}

上一篇下一篇

猜你喜欢

热点阅读