forked from KevinCoble/AIToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.swift
71 lines (57 loc) · 1.85 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
//
// Queue.swift
// AIToolbox
//
// Created by Kevin Coble on 2/20/15.
// Copyright (c) 2015 Kevin Coble. All rights reserved.
//
import Foundation
class QueueNode<T> {
let queuedItem: T
var nextItemInQueue : QueueNode<T>?
init(itemToQueue: T) {
queuedItem = itemToQueue
}
}
open class Queue<T> {
var itemCount: Int = 0
var queueHead : QueueNode<T>?
var queueTail : QueueNode<T>?
public init() {}
/// Computed property to get the number of items queued
open var queuedItemCount : Int {return itemCount}
/// Computed property to determine if a queue is empty
open var isEmpty: Bool {return itemCount == 0}
/// Method to add an item to the queue
open func enqueue(_ itemToQueue: T) {
let newNode = QueueNode<T>(itemToQueue: itemToQueue)
if (itemCount == 0) {
// First item in becomes both head and tail
queueHead = newNode
queueTail = newNode
} else {
// All other items become the new tail
queueTail?.nextItemInQueue = newNode
queueTail = newNode
}
itemCount += 1
}
/// Method to get the item at the front of the queue. The item is removed from the queue
open func dequeue() -> T? {
// If no items, return nil
if (itemCount == 0) {return nil}
// Remove the head node
let headNode = queueHead
queueHead = headNode?.nextItemInQueue
// Lower the count
itemCount -= 1
if (itemCount == 0) { queueTail = nil}
return headNode!.queuedItem
}
/// Method to examine the next item in the queue, without removing it
open func peek() -> T? {
// If no items, return nil
if (itemCount == 0) {return nil}
return queueHead?.queuedItem
}
}