Skip to content

Instantly share code, notes, and snippets.

@AshishKapoor
Created May 13, 2017 14:08
Show Gist options
  • Save AshishKapoor/7de112ad99662be4b0a647567c598b2f to your computer and use it in GitHub Desktop.
Save AshishKapoor/7de112ad99662be4b0a647567c598b2f to your computer and use it in GitHub Desktop.
Stack and Generics implementation in Swift 3.1
import UIKit
// Stack and Generics implementation in Swift 3.1
class Node<T> {
let value: T
var nextNode: Node<T>?
var prevNode: Node<T>?
init(value: T) {
self.value = value
}
}
class Stack<T> {
var top: Node<T>?
func push(_ value: T) {
let oldTop = top
top = Node(value: value)
top?.nextNode = oldTop
}
func pop() -> T? {
let currentTop = top
top = top?.nextNode
return currentTop?.value
}
func peek() -> T? {
return top?.value
}
}
let stack = Stack<Int>()
stack.push(12)
stack.push(22)
stack.push(32)
stack.pop()
stack.pop()
stack.pop()
stack.pop()
struct Users {
let name: String
let userName: String
}
let me = Users(name: "Ashish", userName: "@Kapoor")
let you = Users(name: "You", userName: "@You")
let usersStack = Stack<Users>()
usersStack.push(me)
usersStack.push(you)
print(usersStack.peek()?.name ?? "")
print(usersStack.peek()?.userName ?? "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment