Created
October 31, 2015 18:55
-
-
Save jgrana/b10c18312fa050e012e3 to your computer and use it in GitHub Desktop.
Generic swift queue
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
private class QueueItem<T> { | |
let value: T! | |
var next: QueueItem? | |
init(_ newvalue: T?) { | |
self.value = newvalue | |
} | |
} | |
public class Queue<T> { | |
typealias Element = T | |
private var front: QueueItem<Element> | |
private var back: QueueItem<Element> | |
public init() { | |
back = QueueItem(nil) | |
front = back | |
} | |
public func enqueue(value: Element) { | |
back.next = QueueItem(value) | |
back = back.next! | |
} | |
public func dequeue() -> Element? { | |
if let newhead = front.next { | |
front = newhead | |
return newhead.value | |
} else if let value = front.value { | |
empty() | |
return value | |
} else { | |
return nil | |
} | |
} | |
public func peek() -> Element? { | |
return front.next?.value | |
} | |
public func isEmpty() -> Bool { | |
return front === back | |
} | |
public func empty() { | |
back = QueueItem(nil) | |
front = back | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment