Created
August 14, 2016 17:24
-
-
Save joanmolinas/86685829ff3de8d3c5b4623b3e73e86b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Foundation | |
class Stack<T> { | |
private typealias Node = StackNode<T> | |
private var _top : Node? | |
private var _size : UInt = 0 | |
//MARK: Public API | |
internal func empty() -> Bool { | |
return self._top == nil | |
} | |
internal func size() -> UInt { | |
return self._size | |
} | |
internal func top() -> T? { | |
return self._top?.value | |
} | |
internal func push(node : T?) throws { | |
guard let n = node else { | |
throw ManipulationErrors.InsertNilElement | |
} | |
if let top = self._top { | |
let nextNode = Node() | |
nextNode.value = n | |
nextNode.next = top | |
self._top = nextNode | |
} else { | |
self._top = Node() | |
self._top!.value = n; | |
} | |
self._size += 1; | |
} | |
internal func pop() throws { | |
guard let n = self._top else { | |
throw ManipulationErrors.PopEmpty | |
} | |
self._top = n.next | |
self._size -= 1 | |
} | |
} | |
extension Stack : CustomStringConvertible { | |
var description: String { | |
var debug = "<\(Stack.self)> [" | |
while !self.empty() { | |
debug += "\(self.top()!)" | |
if self.size() != 1 { | |
debug += "," | |
} | |
do { try self.pop() } | |
catch {} | |
} | |
debug += "]" | |
return debug | |
} | |
} |
This file contains hidden or 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 Foundation | |
class StackNode<T> { | |
var value : T! | |
var next : StackNode? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment