You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/zh-hant/codes/swift/chapter_stack_and_queue/array_queue.swift

114 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: array_queue.swift
* Created Time: 2023-01-11
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
class ArrayQueue {
private var nums: [Int] //
private var front: Int //
private var _size: Int //
init(capacity: Int) {
//
nums = Array(repeating: 0, count: capacity)
front = 0
_size = 0
}
/* */
func capacity() -> Int {
nums.count
}
/* */
func size() -> Int {
_size
}
/* */
func isEmpty() -> Bool {
size() == 0
}
/* */
func push(num: Int) {
if size() == capacity() {
print("佇列已滿")
return
}
// + 1
// rear
let rear = (front + size()) % capacity()
// num
nums[rear] = num
_size += 1
}
/* */
@discardableResult
func pop() -> Int {
let num = peek()
//
front = (front + 1) % capacity()
_size -= 1
return num
}
/* */
func peek() -> Int {
if isEmpty() {
fatalError("佇列為空")
}
return nums[front]
}
/* */
func toArray() -> [Int] {
//
(front ..< front + size()).map { nums[$0 % capacity()] }
}
}
@main
enum _ArrayQueue {
/* Driver Code */
static func main() {
/* */
let capacity = 10
let queue = ArrayQueue(capacity: capacity)
/* */
queue.push(num: 1)
queue.push(num: 3)
queue.push(num: 2)
queue.push(num: 5)
queue.push(num: 4)
print("佇列 queue = \(queue.toArray())")
/* */
let peek = queue.peek()
print("佇列首元素 peek = \(peek)")
/* */
let pop = queue.pop()
print("出列元素 pop = \(pop),出列後 queue = \(queue.toArray())")
/* */
let size = queue.size()
print("佇列長度 size = \(size)")
/* */
let isEmpty = queue.isEmpty()
print("佇列是否為空 = \(isEmpty)")
/* */
for i in 0 ..< 10 {
queue.push(num: i)
queue.pop()
print("\(i) 輪入列 + 出列後 queue = \(queue.toArray())")
}
}
}