forked from waynewbishop/bishop-algorithms-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.swift
136 lines (77 loc) · 2.21 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
//
// Queue.swift
// SwiftStructures
//
// Created by Wayne Bishop on 7/11/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
public class Queue<T> {
private var top: QNode<T>!
init() {
top = QNode<T>()
}
//the number of items
var count: Int {
if (top.key == nil) {
return 0
}
else {
var current: QNode<T> = top
var x: Int = 1
//cycle through the list of items
while (current.next != nil) {
current = current.next
x += 1
}
return x
}
}
//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) {
//check top node
if (top.key == nil) {
top.key = key
return
}
let childToUse: QNode<T> = QNode<T>()
var current: QNode<T> = top
//cycle through the list
while (current.next != nil) {
current = current.next
}
//append a new item
childToUse.key = key
current.next = childToUse
}
//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 = QNode<T>()
}
return queueitem
}
} //end class