Chapter 6: Stack Data Structure
Last updated
Last updated
public struct Stack<Element> {
private var storage: [Element] = []
public init() {}
}
extension Stack: CustomStringConvertible {
public var description: String {
let topDivider = "----頂端----\n"
let bottomDivder = "\n-----------"
let stackElements = storage
.map { "\($0)" }
.reversed()
.joined(separator: "\n")
return topDivider + stackElements + bottomDivder
}
} public mutating func push(_ element: Element) {
storage.append(element)
}
@discardableResult
public mutating func pop() -> Element? {
return storage.popLast()
} public func peek() -> Element? {
return storage.last
}
public var isEmpty: Bool {
return peek() == nil
}