hello-algo/codes/swift/chapter_stack_and_queue/array_queue.swift

116 lines
2.9 KiB
Swift
Raw Normal View History

/**
* File: array_queue.swift
* Created Time: 2023-01-11
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
class ArrayQueue {
private var nums: [Int] //
2023-02-01 03:23:29 +08:00
private var front = 0 //
private var queSize = 0 //
init(capacity: Int) {
//
nums = Array(repeating: 0, count: capacity)
}
/* */
func capacity() -> Int {
nums.count
}
/* */
func size() -> Int {
2023-02-01 03:23:29 +08:00
queSize
}
/* */
func isEmpty() -> Bool {
2023-02-01 03:23:29 +08:00
queSize == 0
}
/* */
func offer(num: Int) {
if size() == capacity() {
print("队列已满")
return
}
2023-02-01 03:23:29 +08:00
// + 1
// rear
int rear = (front + queSize) % capacity();
// num
2023-02-01 03:23:29 +08:00
nums[rear] = num;
queSize++;
}
/* */
@discardableResult
func poll() -> Int {
let num = peek()
2023-02-01 03:23:29 +08:00
//
front = (front + 1) % capacity();
queSize--;
return num;
}
/* 访 */
func peek() -> Int {
if isEmpty() {
fatalError("队列为空")
}
return nums[front]
}
/* */
func toArray() -> [Int] {
//
2023-02-01 03:23:29 +08:00
var res = Array(repeating: 0, count: queSize)
for (i, j) in sequence(first: (0, front), next: { $0 < queSize - 1 ? ($0 + 1, $1 + 1) : nil }) {
res[i] = nums[j % capacity()]
}
return res
}
}
@main
enum _ArrayQueue {
/* Driver Code */
static func main() {
/* */
let capacity = 10
let queue = ArrayQueue(capacity: capacity)
/* */
queue.offer(num: 1)
queue.offer(num: 3)
queue.offer(num: 2)
queue.offer(num: 5)
queue.offer(num: 4)
print("队列 queue = \(queue.toArray())")
/* 访 */
let peek = queue.peek()
print("队首元素 peek = \(peek)")
/* */
let poll = queue.poll()
print("出队元素 poll = \(poll),出队后 queue = \(queue.toArray())")
/* */
let size = queue.size()
print("队列长度 size = \(size)")
/* */
let isEmpty = queue.isEmpty()
print("队列是否为空 = \(isEmpty)")
/* */
for i in 0 ..< 10 {
queue.offer(num: i)
queue.poll()
print("\(i) 轮入队 + 出队后 queue = \(queue.toArray())")
}
}
}