algo/swift/09_queue/ArrayQueue.swift

109 lines
3.0 KiB
Swift
Raw Normal View History

2018-10-11 22:56:35 +08:00
//
// Created by Jiandan on 2018/10/11.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
///
struct ArrayQueue<Element>: Queue {
2018-10-11 22:56:35 +08:00
///
private var items: [Element]
///
private var capacity = 0
///
private var head = 0
///
private var tail = 0
///
/// - parameter defaultElement:
/// - parameter capacity:
init(defaultElement: Element, capacity: Int) {
self.capacity = capacity
items = [Element](repeating: defaultElement, count: capacity)
}
// MARK: Protocol: Queue
var isEmpty: Bool { return head == tail }
var size: Int { return tail - head }
var peek: Element? { return isEmpty ? nil : items[head] }
//
// mutating func enqueue(newElement: Element) -> Bool {
// //
// if tail == capacity {
// return false
// }
//
// items[tail] = newElement
// tail += 1
// return true
// }
//
mutating func enqueue(newElement: Element) -> Bool {
// tail == capacity
if tail == capacity {
//
if head == 0 { return false }
//
for i in head ..< tail {
items[i - head] = items[i]
}
// head tail
tail -= head
head = 0
}
items[tail] = newElement
tail += 1
return true
}
mutating func dequeue() -> Element? {
if isEmpty {
return nil
}
let item = items[head]
head += 1
return item
}
}
/// 使2 Swift Array
/// iOS
struct ArrayQueue2<Element>: Queue {
2018-10-11 22:56:35 +08:00
///
var inArray = [Element]()
///
var outArray = [Element]()
var isEmpty: Bool { return inArray.isEmpty && outArray.isEmpty }
var size: Int { return inArray.count + outArray.count }
// outArray inArray outArray
var peek: Element? { return outArray.isEmpty ? inArray.first : outArray.last }
mutating func enqueue(newElement: Element) -> Bool {
// inArray
inArray.append(newElement)
return true
}
mutating func dequeue() -> Element? {
if outArray.isEmpty {
// inArray outArray
outArray = inArray.reversed()
// inArray
inArray.removeAll()
}
// outArray
return outArray.popLast()
}
}