Created
May 13, 2017 14:08
-
-
Save AshishKapoor/7de112ad99662be4b0a647567c598b2f to your computer and use it in GitHub Desktop.
Stack and Generics implementation in Swift 3.1
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
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