Skip to content

Instantly share code, notes, and snippets.

@AshishKapoor
Created May 13, 2017 13:27
Show Gist options
  • Save AshishKapoor/bcc44398217b47a1702793ebecf75918 to your computer and use it in GitHub Desktop.
Save AshishKapoor/bcc44398217b47a1702793ebecf75918 to your computer and use it in GitHub Desktop.
Stack implementation in Swift 3.1
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