Last active
May 3, 2019 09:22
-
-
Save thbwd/d1cbb9ffc5748fd5d1652732dd34eadf to your computer and use it in GitHub Desktop.
Dead simple Swift queue implementation. Let’s put ARC to work. It’s here anyways.
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
public class Queue<Element> { | |
private class QueueItem { | |
let value: Element | |
var next: QueueItem? | |
init(_ value: Element) { | |
self.value = value | |
} | |
} | |
private var front: QueueItem? | |
private weak var back: QueueItem? | |
public var isEmpty: Bool { | |
return front == nil | |
} | |
public init() {} | |
/// Add a new item to the back of the queue. | |
public func enqueue(_ value: Element) { | |
let item = QueueItem(value) | |
if let back = back { | |
back.next = item | |
} else { | |
front = item | |
} | |
back = item | |
} | |
/// Return and remove the item at the front of the queue. | |
public func dequeue() -> Element? { | |
guard let dequeued = front else { return nil } | |
front = dequeued.next | |
return dequeued.value | |
} | |
public func removeAll() { | |
front = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment