algo/swift/09_queue/CircularQueue.swift
Jiandan e121c388d3 [swift][09_queue][remove] Remove "typealias Element = T".
[swift][09_queue][fix] Fix "size" in "QueueBasedOnLinkedList".
2018-10-13 14:50:22 +08:00

62 lines
1.4 KiB
Swift

//
// Created by Jiandan on 2018/10/11.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
///
struct CircularQueue<Element>: Queue {
///
private var items: [Element]
///
private var capacity = 0
///
private var head = 0
///
private var tail = 0
///
/// - parameter defaultElement:
/// - parameter capacity:
init(defaultElement: Element, capacity: Int) {
self.capacity = capacity
items = [Element](repeating: defaultElement, count: capacity)
}
// MARK: Protocol: Queue
var isEmpty: Bool { return head == tail }
var size: Int {
if tail >= head {
return tail - head
} else {
return (tail + 1) + (capacity - head)
}
}
var peek: Element? { return isEmpty ? nil : items[head] }
mutating func enqueue(newElement: Element) -> Bool {
//
if (tail + 1) % capacity == head {
return false
}
items[tail] = newElement
tail = (tail + 1) % capacity
return true
}
mutating func dequeue() -> Element? {
if isEmpty {
return nil
}
let item = items[head]
head = (head + 1) % capacity
return item
}
}