1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| /// 队列 queue // 用数组来实现队列内部的线性表
public struct Queue<T> { fileprivate var queueArray = [T]() public var count: Int { return queueArray.count } public var isEmpty: Bool { return queueArray.isEmpty } // 前面的元素 public var front: T? { if isEmpty { print("queue is empty") return nil } else { return queueArray.first } } // 添加元素 public mutating func enqueue(_ element: T) { queueArray.append(element) } // 移除元素 public mutating func dequeue() -> T? { if isEmpty { print("queue is empty") return nil } else { return queueArray.removeFirst() } } // 打印元素 public mutating func printAllElements() { guard count > 0 else { print("queue is empty") return } print("\nprint all queue elements:") for (index, value) in queueArray.enumerated() { print("[\(index)]\(value)") } } }
|