ํ

์„ ์ž…์„ ์ถœ(FIFO) : ๋จผ์ €๋“ค์–ด์˜จ ๋†ˆ์ด ๋จผ์ € ๋‚˜๊ฐ€๋Š” ์ž๋ฃŒ๊ตฌ์กฐ

Swift ์—์„œ์˜ ๊ตฌํ˜„

struct Queue<T> {
    private var queue: [T] = []
    
    public var count: Int {
        return queue.count
    }
    
    public var isEmpty: Bool {
        return queue.isEmpty
    }
    
    public mutating func enqueue(_ element: T) {
        queue.append(element)
    }
    
    public mutating func dequeue() -> T? {
        return isEmpty ? nil : queue.removeFirst()
    }
}

๊ทธ๋Ÿฌ๋‚˜ ์ด ๋ฐฉ๋ฒ•์€ dequeue์‹œ์— element๋“ค์ด ์ž๋ฆฌ๋ฅผ ๋‹น๊ธฐ๋Š” ๊ณผ์ •์—์„œ O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

 

Dequeue์— ํšจ์œจ์ ์ธ ํ

struct Queue<T> {
    private var queue: [T?] = []
    private var head: Int = 0
    
    public var count: Int {
        return queue.count - head
    }
    
    public var isEmpty: Bool {
        return count == 0
    }
    
    public mutating func enqueue(_ element: T) {
        queue.append(element)
    }
    
    public mutating func dequeue() -> T? {
        if isEmpty {
            return nil
        }
        
        let element = queue[head]
        queue[head] = nil
        head += 1
        
        if head > 50 {
            queue.removeFirst(head)
            head = 0
        }
        return element
    }
}

์ด ํ๋Š” dequeue์‹œ ๋ฐ˜ํ™˜๋˜์–ด์•ผ ํ•˜๋Š” element์˜ index๋ฅผ ๋“ค๊ณ  ์žˆ์œผ๋ฉฐ, ๋‹น๊ฒจ์˜ค๋Š” ๊ณผ์ •์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— O(1)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง„๋‹ค.

๊ทธ๋ฆฌ๊ณ  queue์˜ 50๊ฐœ ์Œ“์˜€์„ ๋•Œ dequeue๋œ element๋“ค์„ removeํ•ด์ค€๋‹ค.

 

์ถœ์ฒ˜ : https://babbab2.tistory.com/84 (์†Œ๋“ค์ด๋‹˜ ํ‹ฐ์Šคํ† ๋ฆฌ)

 


๊ฐ„๋‹จํ•œ ํ ๊ตฌํ˜„

์ถ”๊ฐ€๋กœ, ์ข€ ๋” ๊ฐ„๋‹จํ•œ ํ ๊ตฌํ˜„์„ ์†Œ๊ฐœํ•œ๋‹ค.

push, pop ๋‘˜๋‹ค ์‹œ๊ฐ„๋ณต์žก๋„ O(1)์ด๋‹ค.

struct Queue<T> {
    var array: [T] = []
    var index = 0
    
    mutating func push(_ element: T) {
        array.append(element)
    }
    
    mutating func pop() -> T? {
        guard index < array.count else {
            return nil
        }
        let element = array[index]
        index += 1
        return element
    }
}

 

๋ฐ˜์‘ํ˜•
JerryiOS