forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularQueue.swift
61 lines (50 loc) · 1.37 KB
/
CircularQueue.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//
// 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
}
}