protocol Stack { associatedtype Element //是否为空 var isEmpty: Bool{ get } //栈的大小 var Size: Int{ get } //栈顶元素 var peek: Element? { get } //入栈 mutating func push(_ newElement:Element) //出栈 mutating func pop()->Element? }
struct IntegerStack:Stack { typealias Element = Int private var stack = [Element]() var isEmpty: Bool {return stack.isEmpty} var Size: Int {return stack.count} var peek: Int? {return stack.last} mutating func push(_ newElement: Int) { self.stack.append(newElement) } func pop() -> Int? { return stack.last } }
protocol Queue { associatedtype Element var isEmpty: Bool {get} var Size: Int {get} var Peek:Element? {get} mutating func enQueue(_ newElement:Element) mutating func deQueue()->Element? }
struct IntergerQueue:Queue { typealias Element = Int private var left = [Element]() private var right = [Element]() var isEmpty: Bool {return left.isEmpty && right.isEmpty} var Size: Int {return left.count + right.count} var Peek: Element? {return left.isEmpty ? right.first : left.last} mutating func enQueue(_ newElement: Int) { right.append(newElement) } mutating func deQueue() -> Element? { if left.isEmpty { left = right.reversed() right.removeAll() } return left.popLast() } }