Created
June 20, 2021 06:34
-
-
Save Aditi3/7e9b0ed1abf8b600870cf12794026331 to your computer and use it in GitHub Desktop.
Implementing Stack Data Structure, LIPO
This file contains hidden or 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
| import UIKit | |
| struct Stack<Element> { | |
| private var storage: [Element] = [] | |
| init() {} | |
| mutating func push(_ element: Element) { | |
| storage.append(element) | |
| } | |
| mutating func pop() -> Element? { | |
| return storage.popLast() | |
| } | |
| } | |
| extension Stack: CustomStringConvertible { | |
| var description: String { | |
| let topDivider = "------top------\n" | |
| let bottomDivider = "\n----------" | |
| let stackElements = storage.map { "\($0)"}.reversed().joined(separator: "\n") | |
| return topDivider + stackElements + bottomDivider | |
| } | |
| } | |
| /// create a Stack | |
| var stack = Stack<Int>() | |
| /// push to Stack | |
| stack.push(10) | |
| stack.push(20) | |
| stack.push(30) | |
| stack.push(40) | |
| stack.push(50) | |
| print("before popping") | |
| print(stack) | |
| print("after popping") | |
| /// pop from Stack | |
| stack.pop() | |
| print(stack) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment