-
Notifications
You must be signed in to change notification settings - Fork 56
/
Deque-Optimized.swift
executable file
·79 lines (66 loc) · 1.55 KB
/
Deque-Optimized.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Deque (pronounced "deck"), a double-ended queue
All enqueuing and dequeuing operations are O(1).
*/
public struct Deque<T> {
private var array: [T?]
private var head: Int
private var capacity: Int
public init(capacity: Int = 10) {
self.capacity = max(capacity, 1)
array = .init(count: capacity, repeatedValue: nil)
head = capacity
}
public var isEmpty: Bool {
return count == 0
}
public var count: Int {
return array.count - head
}
public mutating func enqueue(element: T) {
array.append(element)
}
public mutating func enqueueFront(element: T) {
if head == 0 {
capacity *= 2
let emptySpace = [T?](count: capacity, repeatedValue: nil)
array.insertContentsOf(emptySpace, at: 0)
head = capacity
}
head -= 1
array[head] = element
}
public mutating func dequeue() -> T? {
guard head < array.count, let element = array[head] else { return nil }
array[head] = nil
head += 1
if capacity > 10 && head >= capacity*2 {
let amountToRemove = capacity + capacity/2
array.removeFirst(amountToRemove)
head -= amountToRemove
capacity /= 2
}
return element
}
public mutating func dequeueBack() -> T? {
if isEmpty {
return nil
} else {
return array.removeLast()
}
}
public func peekFront() -> T? {
if isEmpty {
return nil
} else {
return array[head]
}
}
public func peekBack() -> T? {
if isEmpty {
return nil
} else {
return array.last!
}
}
}