ํ
์ ์ ์ ์ถ(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
}
}
๋ฐ์ํ
'๐ป CS > ์๋ฃ๊ตฌ์กฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ํ(Heap) ๊ตฌํํด๋ณด๊ธฐ (0) | 2023.04.11 |
---|---|
[Swift] ๊ทธ๋ํ(Graph) (0) | 2023.03.29 |
[Swift] ๋ฑ ๊ตฌํํด๋ณด๊ธฐ (0) | 2023.03.29 |
[Swift] ์คํ ๊ตฌํํด๋ณด๊ธฐ (0) | 2023.03.29 |
๋ฉ๋ชจ๋ฆฌ ๊ตฌ์กฐ (0) | 2023.03.23 |