protocol Queue{
//持有元素类型
associatedtype Element
//是否为空
var isEmpty : Bool{get}
//队首元素
var peek : Element?{get}
//队列长度
var size : Int {get}
//进队
mutating func enqueue(_ element : Element)
//出队
mutating func dequeue() -> Element?
}
struct IntegerQueue : Queue{
typealias Element = Int
//是否为空
var isEmpty : Bool{return left.isEmpty && right.isEmpty}
//队首元素
var peek : Element?{left.isEmpty ? right.first : left.last}
//队列长度
var size : Int {return left.count + right.count}
//进队
mutating func enqueue(_ element : Element){
right.append(element)
}
//出队
mutating func dequeue() -> Element?{
if left.isEmpty{
left = right.reversed()
right.removeAll()
}
return left.popLast()
}
var left = [Element]()
var right = [Element]()
}
网友评论