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_deque.swift

149 lines
4.0 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_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)")
}
}