iOS 中的 NSOperationQueue 就是一种队列结构,遵循 FIFO 的原则,将 NSOperation 任务添加到队列中去,并挨个取出执行任务.
今天用 swift 代码来实现一个队列结构,使其具备一下特点
1 能够插入一个新的元素到队列尾
2 能够从队列头取出一个元素
3 能够清空队列中的所有元素
4 能够遍历队列中所有元素
5 当队列为空或者满的时候不进行插入和取出的任何操作.
一 : 创建一个队列
init(capacity : Int) { // 构造函数创建出一个队列数据模型来
queue_Capacity = capacity
self.clearQueue()
}
/// 清空队列
open func clearQueue() {
self.queue = [T]()
queue_Length = 0
queue_Head = 0
queue_Tail = 0
}
二 : 队列判断为空 或为满, 队列元素长度
/// 获取队列元素的长度
open func queueLength() -> Int {
return queue_Length
}
/// 判断队列是否已经满了
open func queueFull() -> Bool {
return queue_Length == queue_Capacity
}
/// 判断队列是否为空
open func queueEmpty() -> Bool {
return queue_Length == 0;
}
三 : 入队列,在队列尾部位置插入一个元素
/// 往队列中添加一个元素
open func enQueue(_ element : String) -> Bool {
if queueFull() {
return false
} else {
self.queue?.insert(element, at: queue_Tail)
queue_Tail+=1;
queue_Tail = queue_Tail % queue_Capacity
queue_Length+=1;
return true
}
}
四 : 出队列,在队列头部位置取出一个元素
/// 从队列中取出来一个元素 如果队列为空 那么 取出来的为 nil
open func deQueue() -> String? {
if queueEmpty() {
return nil
} else {
let element = self.queue?[queue_Head]
queue_Head+=1;
queue_Head = queue_Head % queue_Capacity
queue_Length-=1;
return element;
}
}
五 : 遍历队列中所有元素,检查队列插入 取出元素后的变化
/// 遍历队列
open func queueTraverse() {
let total = queue_Length + queue_Head
let start = queue_Head
for i in start..<total {
let sum = self.queue?[i%queue_Capacity]
print("\n\(sum),\n")
}
}
下边是代码结合 UI 展示队列插入 取出,清空的操作
Untitled.gif