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

149 lines
4 KiB
Swift
Raw Permalink Normal View History

/**
* 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 _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
}
/* */
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
_size += 1
}
/* */
func pushLast(num: Int) {
if size() == capacity() {
print("双向队列已满")
return
}
// + 1
let rear = index(i: front + size())
// num
nums[rear] = num
_size += 1
}
/* */
func popFirst() -> Int {
let num = peekFirst()
//
front = index(i: front + 1)
_size -= 1
return num
}
/* */
func popLast() -> Int {
let num = peekLast()
_size -= 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] {
//
(front ..< front + size()).map { nums[index(i: $0)] }
}
}
@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)")
}
}