-
Notifications
You must be signed in to change notification settings - Fork 276
/
Queue.swift
115 lines (69 loc) · 1.84 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//
// Queue.swift
// SwiftStructures
//
// Created by Wayne Bishop on 7/11/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
class Queue<T> {
private var top: Node<T>?
private var counter: Int = 0
init() {
top = Node<T>()
}
//the number of items
var count: Int {
return counter
}
//MARK: Supporting Functions
//retrieve the top most item
func peek() -> T? {
return top?.key
}
//check for the presence of a value
func isEmpty() -> Bool {
guard top?.key != nil else {
return true
}
return false
}
//MARK: Queuing Functions
//enqueue the specified object
func enQueue(_ key: T) {
//trivial case
guard top?.key != nil else {
top?.key = key
counter += 1
return
}
let childToUse = Node<T>()
var current = top
//cycle through the list
while current?.next != nil {
current = current?.next
}
//append new item
childToUse.key = key
current?.next = childToUse
counter += 1
}
//retrieve items from the top level - O(1) time
func deQueue() -> T? {
//determine key instance
guard top?.key != nil else {
return nil
}
//retrieve and queue the next item
let queueItem: T? = top?.key
//use optional binding
if let nextItem = top?.next {
top = nextItem
}
else {
top = Node<T>()
}
counter -= 1
return queueItem
}
} //end class