Swift, Data Structure, Queue

양쪽에 구멍을 뚫은 프링글스통에 있는 프링글스를 생각하며..

Posted by MinJun on Monday, June 18, 2018 Tags: Algorithm DataStructure Swift   4 minute read

Code

// 0
func example(str: String, isAction: Bool = true, action: () -> Void) {
    print("---------\(str), isAction: \(isAction)---------")
    
    if isAction {
        action()
    }
}

// 1
struct Queue<T> {
    fileprivate var data: [T] = [T]()
    public init() {}
    
    public init<S: Sequence>(_ elements: S) where S.Iterator.Element == T  {
        data.append(contentsOf: elements)
    }
    
    mutating func enqueue(element: T)  {
        data.append(element)
    }
    
    mutating func dequeue() -> T? {
        return data.removeFirst()
    }
    
    mutating func peek() -> T? {
        return data.first
    }
    
    mutating func clear() {
        data.removeAll()
    }
    
    public var count: Int {
        return data.count
    }
    
    public var capacity: Int {
        get {
            return data.capacity
        }set {
            return data.reserveCapacity(newValue)
        }
    }
    
    var isFull: Bool {
        return data.capacity == data.count
    }
    
    var isEmpty: Bool {
        return data.isEmpty
    }
}

// 2
extension Queue: CustomStringConvertible, CustomDebugStringConvertible {
    
    public var description: String {
        return self.data.description
    }
    
    public var debugDescription: String {
        return self.data.debugDescription
    }
}

// 3
extension Queue: ExpressibleByArrayLiteral {
    public init(arrayLiteral elements: T...) {
        data = elements
    }
}

// 4
extension Queue: Sequence {
    func makeIterator() -> AnyIterator<T> {
        return AnyIterator(IndexingIterator(_elements: data.lazy))
    }
}

// 5
example(str: "Queue") {
    var q1: Queue<Int> = [1,2,3,4,5]
    var q2 = Queue<Int>()
    q1.dequeue()
    print(q1)
    print(q2)
    
    q2.enqueue(element: 55)
    for el in q1 {
        print(el)
    }
    
    q1.clear()
    print(q1)
}

큐는 먼저 입력된 데이터가 먼저 출력되는 FIFO(first in First Out) 데이터 구조를 나타냅니다.

전체 코드 주소


Reference

swift-algorithm-club/Queue