Last active
April 9, 2020 07:32
-
-
Save derekcoder/efad42c58156f3c0a49241c5c01f2105 to your computer and use it in GitHub Desktop.
The implementation of Stack data structure in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Stack.swift | |
// | |
// Created by Derek on 18/12/19. | |
// Copyright © 2019 DerekCoder. All rights reserved. | |
// | |
public struct Stack<Element> { | |
private var storage: [Element] = [] | |
public init() {} | |
public init(_ elements: [Element]) { | |
storage = elements | |
} | |
public mutating func push(_ element: Element) { | |
storage.append(element) | |
} | |
@discardableResult | |
public mutating func pop() -> Element? { | |
storage.popLast() | |
} | |
public func peek() -> Element? { | |
storage.last | |
} | |
public var isEmpty: Bool { | |
peek() == nil | |
} | |
} | |
extension Stack: CustomStringConvertible { | |
public var description: String { | |
""" | |
---- top ---- | |
\(storage.map { "\($0)" }.reversed().joined(separator: "\n")) | |
------------- | |
""" | |
} | |
} | |
extension Stack: ExpressibleByArrayLiteral { | |
public init(arrayLiteral elements: Element...) { | |
storage = elements | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment