Skip to content

Instantly share code, notes, and snippets.

@Daemon-Devarshi
Created September 3, 2017 15:28
Show Gist options
  • Save Daemon-Devarshi/7d0370bcdd65cb254c88cd95290f3f3e to your computer and use it in GitHub Desktop.
Save Daemon-Devarshi/7d0370bcdd65cb254c88cd95290f3f3e to your computer and use it in GitHub Desktop.
Implementation of a stack in swift which performs push, pop and peek operations with O(1) complexity
class Stack {
var lastNode: Node? = nil
class Node {
var data: Int!
var prev: Node?
init(data: Int, prev: Node?) {
self.data = data
self.prev = prev
}
}
func peek() -> Int? {
if let lastNode = lastNode {
return lastNode.data
} else {
return nil
}
}
func pop() -> Int? {
if let lastNode = lastNode {
let data = lastNode.data
self.lastNode = nil
self.lastNode = lastNode.prev
return data
} else {
return nil
}
}
func push(element: Int) {
let node = Node(data:element, prev:lastNode)
lastNode = node
}
}
var stack = Stack()
stack.pop() // returns nil
stack.push(element: 24) // 24
stack.push(element: 35) // 24, 35
stack.push(element: 42) // 24, 35, 42
stack.pop() // 24, 35 -> 42
stack.pop() // 24 -> 35
stack.pop() // nil -> 24
stack.pop() // nil -> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment