algo/swift/09_queue/ArrayQueue.swift
Jiandan e121c388d3 [swift][09_queue][remove] Remove "typealias Element = T".
[swift][09_queue][fix] Fix "size" in "QueueBasedOnLinkedList".
2018-10-13 14:50:22 +08:00

109 lines
3.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Created by Jiandan on 2018/10/11.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
///
struct ArrayQueue<Element>: Queue {
///
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 {
///
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()
}
}