Skip to content

Instantly share code, notes, and snippets.

@yossan
Created November 18, 2018 13:14
Show Gist options
  • Save yossan/96c225a9714e4a334f5683a91edf4a44 to your computer and use it in GitHub Desktop.
Save yossan/96c225a9714e4a334f5683a91edf4a44 to your computer and use it in GitHub Desktop.
Queue with Array
struct Queue <Element> {
var head: Int = 0
var tail: Int = 0
var size: Int = 0
let data:UnsafeMutableBufferPointer<Element>
init(size: Int) {
self.data = UnsafeMutableBufferPointer<Element>.allocate(capacity: size+1)
self.size = size + 1
}
var isEmpty: Bool {
return head == tail
}
var isFilled: Bool {
return head == (tail + 1) % self.size
}
mutating func enqueue(_ element: Element) {
precondition(self.isFilled == false)
self.data[tail] = element
tail = (tail + 1) % self.size
}
@discardableResult
mutating func dequeue() -> Element {
precondition(self.isEmpty == false)
defer { self.head = (self.head + 1) % self.size }
return self.data[head]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment