-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.swift
146 lines (90 loc) · 2.59 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
133
134
135
136
137
138
139
140
141
142
143
//
// Queue.swift
// SwiftStructures
//
// Created by Wayne Bishop on 7/11/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
//generic queue node
class QNode<T> {
var key: T? = nil
var next: QNode? = nil
}
public class Queue<T> {
private var top: QNode<T>! = 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
}
}
//enqueue the specified object
func enQueue(key: T) {
//check for the instance
if (top == nil) {
top = QNode<T>()
}
//establish the top node
if (top.key == nil) {
top.key = key
return
}
let childToUse: QNode<T> = QNode<T>()
var current: QNode = top
//cycle through the list of items to get to the end.
while (current.next != nil) {
current = current.next!
}
//append a new item
childToUse.key = key
current.next = childToUse
}
//retrieve the top most item
func peek() -> T? {
return top.key!
}
//retrieve items from the top level in O(1) constant time
func deQueue() -> T? {
//determine if the key or instance exist
let topitem: T? = self.top?.key
if (topitem == nil) {
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
}
//check for the presence of a value
func isEmpty() -> Bool {
//determine if the key or instance exist
if let _: T = self.top?.key {
return false
}
else {
return true
}
}
func clear() {
while !isEmpty() {
deQueue()
}
}
} //end class