hello-algo/codes/swift/chapter_stack_and_queue/array_deque.swift
Yudong Jin f68bbb0d59
Update the book based on the revised second edition (#1014)
* Revised the book

* Update the book with the second revised edition

* Revise base on the manuscript of the first edition
2023-12-28 18:06:09 +08:00

152 lines
4.1 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_deque.swift
* Created Time: 2023-02-22
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
class ArrayDeque {
private var nums: [Int] //
private var front: Int //
private var queSize: Int //
/* */
init(capacity: Int) {
nums = Array(repeating: 0, count: capacity)
front = 0
queSize = 0
}
/* */
func capacity() -> Int {
nums.count
}
/* */
func size() -> Int {
queSize
}
/* */
func isEmpty() -> Bool {
size() == 0
}
/* */
private func index(i: Int) -> Int {
//
// i
// i
(i + capacity()) % capacity()
}
/* */
func pushFirst(num: Int) {
if size() == capacity() {
print("双向队列已满")
return
}
//
// front
front = index(i: front - 1)
// num
nums[front] = num
queSize += 1
}
/* */
func pushLast(num: Int) {
if size() == capacity() {
print("双向队列已满")
return
}
// + 1
let rear = index(i: front + size())
// num
nums[rear] = num
queSize += 1
}
/* */
func popFirst() -> Int {
let num = peekFirst()
//
front = index(i: front + 1)
queSize -= 1
return num
}
/* */
func popLast() -> Int {
let num = peekLast()
queSize -= 1
return num
}
/* 访 */
func peekFirst() -> Int {
if isEmpty() {
fatalError("双向队列为空")
}
return nums[front]
}
/* 访 */
func peekLast() -> Int {
if isEmpty() {
fatalError("双向队列为空")
}
//
let last = index(i: front + size() - 1)
return nums[last]
}
/* */
func toArray() -> [Int] {
//
var res = Array(repeating: 0, count: size())
for (i, j) in sequence(first: (0, front), next: { $0 < self.size() - 1 ? ($0 + 1, $1 + 1) : nil }) {
res[i] = nums[index(i: j)]
}
return res
}
}
@main
enum _ArrayDeque {
/* Driver Code */
static func main() {
/* */
let deque = ArrayDeque(capacity: 10)
deque.pushLast(num: 3)
deque.pushLast(num: 2)
deque.pushLast(num: 5)
print("双向队列 deque = \(deque.toArray())")
/* 访 */
let peekFirst = deque.peekFirst()
print("队首元素 peekFirst = \(peekFirst)")
let peekLast = deque.peekLast()
print("队尾元素 peekLast = \(peekLast)")
/* */
deque.pushLast(num: 4)
print("元素 4 队尾入队后 deque = \(deque.toArray())")
deque.pushFirst(num: 1)
print("元素 1 队首入队后 deque = \(deque.toArray())")
/* */
let popLast = deque.popLast()
print("队尾出队元素 = \(popLast),队尾出队后 deque = \(deque.toArray())")
let popFirst = deque.popFirst()
print("队首出队元素 = \(popFirst),队首出队后 deque = \(deque.toArray())")
/* */
let size = deque.size()
print("双向队列长度 size = \(size)")
/* */
let isEmpty = deque.isEmpty()
print("双向队列是否为空 = \(isEmpty)")
}
}