[Data Structures] Queue - Doubly Linked List based Implementation

Queue

์š”๋ฒˆ์—๋Š” Doubly Linked List๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ตฌํ˜„ํ•œ ์ฝ”๋“œ๋ฅผ ์‚ดํŽด๋ณธ๋‹ค. Doubly Linked List ์ฝ”๋“œ๋Š” ์ฐธ๊ณ  ๋งํฌ ๋ฅผ ํ™•์ธํ–ˆ๋‹ค.

Doubly Linked List๋กœ Queue ๊ตฌํ˜„ํ•ด๋ณด๊ธฐ

class QueueLinkedList<T>: Queue {
    private var linkedList = DoublyLinkedList<T>()
    
    var isEmpty: Bool {
        linkedList.isEmpty
    }
    
    var peek: T? {
        linkedList.first?.value
    }
    
    init() {}
    
    func enqueue(_ element: T) -> Bool {
        linkedList.append(element)
        return true
    }
    
    func dequeue() -> T? {
        guard !linkedList.isEmpty, let element = linkedList.first else {
            return nil
        }
        return linkedList.remove(element)
    }
}

์•ž ํฌ์ŠคํŒ…์—์„œ ๋งŒ๋“ค์–ด๋‘” Queue ํ”„๋กœํ† ์ฝœ์„ ์ฑ„ํƒํ•œ ๋’ค ์š”๊ตฌ ์‚ฌํ•ญ์— ๋งž๊ฒŒ ๊ตฌํ˜„ํ–ˆ๋‹ค. Doubly Linked List๊ฐ€ ์—†์—ˆ๋‹ค๋ฉด ๊ตฌํ˜„ํ•  ์ˆ˜ ์—†์„โ€ฆ

์‹คํ–‰ ๊ฒฐ๊ณผ ๋ฐ ๋ณต์žก๋„ ์ •๋ฆฌ

  • ์‹คํ–‰ ๊ฒฐ๊ณผ

image

  • ๋ณต์žก๋„

image

QueueArray๋Š” ํ์—์„œ element๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋ฐ O(n)์˜ ์‹œ๊ฐ„์ด ๊ฑธ๋ ธ์—ˆ์ง€๋งŒ ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•œ๋‹ค๋ฉด O(1)๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. (๋ฐฐ์—ด์€ ์•ž์œผ๋กœ ํ•œ์นธ์‹ ๋•ก๊ฒจ์•ผ๋˜์ง€๋งŒ ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ๋Š” ๋…ธ๋“œ๋งŒ ํ•ด์ œํ•˜๋ฉด ๋˜๋‹ˆ๊นŒ.)

ํ•˜์ง€๋งŒ ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ๋Š” ์ธ์Šคํ„ด์Šค ๋‚ด๋ถ€์—์„œ prev์™€ next๋ฅผ ์ฐธ์กฐํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ๋†’์€ ํŽธ์ด๋‹ค. ๊ฑฐ๊ธฐ์— element๋ฅผ ์ถ”๊ฐ€ํ•  ๋•Œ๋งˆ๋‹ค ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜๋ฏ€๋กœ Array์— ๋น„ํ•ด ๋น„์šฉ์ด ๋งŽ์ด ๋“œ๋Š” ๋™์  ํ• ๋‹น์ด ํ•„์š”ํ•˜๋‹ค.

์›๋ž˜๋Š” ์ด๊ฒƒ๋•Œ๋ฌธ์— ๋ง๋ฒ„ํผ๋ฅผ ์‚ดํŽด๋ด์•ผ ํ•˜์ง€๋งŒโ€ฆ ๋ฐ”์˜๋ฏ€๋กœ ๊ทธ๋ƒฅ ๋ฐ”๋กœ ์Šคํƒ ๋‘๊ฐœ๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๊ฑธ ์•Œ์•„๋ณด๋Ÿฌ ๊ฐ„๋‹ค.

Leave a comment