Created
May 13, 2017 13:27
-
-
Save AshishKapoor/bcc44398217b47a1702793ebecf75918 to your computer and use it in GitHub Desktop.
Stack 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 implementation in Swift 3.1 | |
class Node { | |
let value: Int | |
var nextNode: Node? | |
init(value: Int) { | |
self.value = value | |
} | |
} | |
class Stack { | |
var top: Node? | |
func push(_ value: Int) { | |
let oldTop = top | |
top = Node(value: value) | |
top?.nextNode = oldTop | |
} | |
func pop() -> Int? { | |
let currentTop = top | |
top = top?.nextNode | |
return currentTop?.value | |
} | |
} | |
let stack = Stack() | |
stack.push(12) | |
stack.push(22) | |
stack.push(32) | |
stack.pop() // 32 | |
stack.pop() // 22 | |
stack.pop() // 12 | |
stack.pop() // nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment