hello-algo/codes/swift/chapter_stack_and_queue/array_queue.swift
nuomi1 7359a7cb4b
Review Swift codes (#1150)
* feat(swift): review for chapter_computational_complexity

* feat(swift): review for chapter_data_structure

* feat(swift): review for chapter_array_and_linkedlist

* feat(swift): review for chapter_stack_and_queue

* feat(swift): review for chapter_hashing

* feat(swift): review for chapter_tree

* feat(swift): add codes for heap article

* feat(swift): review for chapter_heap

* feat(swift): review for chapter_graph

* feat(swift): review for chapter_searching

* feat(swift): review for chapter_sorting

* feat(swift): review for chapter_divide_and_conquer

* feat(swift): review for chapter_backtracking

* feat(swift): review for chapter_dynamic_programming

* feat(swift): review for chapter_greedy

* feat(swift): review for utils

* feat(swift): update ci tool

* feat(swift): trailing closure

* feat(swift): array init

* feat(swift): map index
2024-03-20 21:15:39 +08:00

113 lines
2.8 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.

/**
* 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())")
}
}
}