-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.swift
55 lines (46 loc) · 944 Bytes
/
Queue.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
class Queue<T> {
private class Node<T> {
var val: T, next: Node<T>?
init(_ val: T) {
self.val = val
}
}
private var head: Node<T>?
private var tail: Node<T>?
init() {}
var size = 0
var front: T {
head!.val
}
var rear: T {
tail!.val
}
var isEmpty: Bool {
head == nil
}
func enqueue(_ val: T?) {
guard let val = val else { return }
let node = Node(val)
if let tail = tail {
tail.next = node
} else {
head = node
}
tail = node
size += 1
}
func dequeue() {
if head === tail {
head = nil
tail = nil
} else {
head = head?.next
}
size = max(0, size - 1)
}
deinit {
while !isEmpty {
dequeue()
}
}
}