Skip to content

Instantly share code, notes, and snippets.

@PraveenKommuri
Created April 15, 2021 21:23
Show Gist options
  • Save PraveenKommuri/2411c66d47295f495fa87b5713b7d0a9 to your computer and use it in GitHub Desktop.
Save PraveenKommuri/2411c66d47295f495fa87b5713b7d0a9 to your computer and use it in GitHub Desktop.
Implemented Stack Data Structure with/without Generics
//Without using generics
struct StackEx {
private var items: [Any] = []
mutating func push(item: Any) { items.append(item) }
mutating func pop() -> Any { items.popLast() as Any }
var top: Any { return items.last as Any }
mutating func getAll() -> [Any] { return items }
}
var stacktEx = StackEx()
stacktEx.push(item: 10); stacktEx.push(item: 11); stacktEx.push(item: 12)
stacktEx.getAll()
stacktEx.pop()
stacktEx.getAll()
stacktEx.top
// Using Generic.
struct GenericStack<ItemType> {
private var items: [ItemType] = []
mutating func push(item: ItemType) { items.append(item) }
mutating func pop() { items.popLast() }
var top: ItemType? { return items.last }
mutating func getAll() -> [ItemType]? { return items }
}
var intStack = GenericStack<Int>()
intStack.push(item: 10); intStack.push(item: 11); intStack.push(item: 12); intStack.push(item: 13)
intStack.getAll()
intStack.pop()
intStack.getAll()
intStack.top
var strStack = GenericStack<String>()
strStack.push(item: "a"); strStack.push(item: "b"); strStack.push(item: "c")
strStack.getAll()
strStack.pop()
strStack.getAll()
strStack.top
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment