Created
August 14, 2016 17:22
-
-
Save joanmolinas/1243d7854d6596f0542067da1fa067a5 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 Queue<T> { | |
private typealias Node = QueueNode<T> | |
private var _top : Node? | |
private var _last : 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 front() -> T? { | |
return self._top?.value | |
} | |
internal func back() -> T? { | |
return self._last?.value | |
} | |
internal func push(node : T?) throws { | |
guard let n = node else { | |
throw ManipulationErrors.InsertNilElement | |
} | |
if let _ = self._top { | |
let newNode = Node() | |
newNode.value = n | |
self._last?.next = newNode | |
self._last = newNode | |
} else { | |
self._top = Node() | |
self._top?.value = n | |
self._last = self._top | |
} | |
self._size += 1 | |
} | |
internal func pop() throws { | |
guard let _ = self._top else { | |
throw ManipulationErrors.PopEmpty | |
} | |
self._top = self._top?.next | |
self._size -= 1 | |
} | |
} | |
extension Queue : CustomStringConvertible { | |
var description: String { | |
var debug = "<\(Queue.self)> [" | |
while !self.empty() { | |
debug += "\(self.front()!)" | |
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 QueueNode<T> { | |
var value : T! | |
var next : QueueNode? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment