swift用队列实现栈

2019-10-16  本文已影响0人  前年的邂逅_Jerry

class ViewController: UITableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var stack = MyStack()
        stack.push(1)
        stack.push(2)
        stack.push(3)
        stack.push(4)
        stack.push(5)
        stack.push(6)
        stack.push(7)
        
        print(stack.peek)
        print(stack.peek)
        print(stack.pop())
        print(stack.peek)
        print(stack.pop())
    }
}

struct MyStack {
    var queueA = MyQueue()
    var queueB = MyQueue()
    
    var size : Int{return queueA.size}
    
    var isEmpty : Bool{return queueA.isEmpty}
    //将要出栈的元素
    var peek : Int?{
        mutating get{
            shift()
            if let element = queueA.peek{
                queueA.dequeue()
                queueB.enqueue(element)
                swap()
                return element
            }else{
                return nil
            }
        }
    }
    mutating func push(_ val : Int){
        queueA.enqueue(val)
    }
    mutating func pop() -> Int?{
        shift()
        swap()
        return queueB.dequeue()
    }
    mutating func shift(){
        while queueA.size != 1 {
            if let element = queueA.dequeue(){
                queueB.enqueue(element)
            }
        }
    }
    mutating func swap(){
        (queueA , queueB) = (queueB , queueA)
    }
}

protocol Queue {
    associatedtype Element
    
    var isEmpty : Bool{get}
    var size : Int{get}
    var peek : Int?{get}
    //入队
    mutating func enqueue(_ val : Element)
    //出队
    mutating func dequeue() -> Element?
}

struct MyQueue : Queue {
    
    typealias Element = Int
    
    var left = [Element]()
    var right = [Element]()
    var peek : Element?{
        return left.isEmpty ? right.last : left.first
    }
    var isEmpty : Bool{return left.isEmpty && right.isEmpty}
    var size : Int{return left.count + right.count}
    //入队
    mutating func enqueue(_ val : Element){
        left.append(val)
    }
    //出队
    mutating func dequeue() -> Element?{
        if left.isEmpty{
            
        }else{
            while (!left.isEmpty){
                if let element = left.popLast(){
                    right.append(element)
                }
            }
        }
        return right.popLast()
    }
}

上一篇 下一篇

猜你喜欢

热点阅读