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/codes/swift/chapter_stack_and_queue/array_deque.swift

153 lines
4.1 KiB

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