๐ง ์๋ฃ๊ตฌ์กฐ ์ค, ์ ํ๊ตฌ์กฐ์ ๋ํ์ ์ธ Stack๊ณผ Queue์ ๋ํด ์ ๋ฆฌ๋ฅผ ํด๋ณด์์ต๋๋ค.
Stack์ ๋์์๋ง data๊ฐ ์ถ๊ฐ ๋๋ ์ ๊ฑฐ๋ฅผ ํ๋ ์๋ฃ๊ตฌ์กฐ๋ก Data๋ฅผ ์ถ๊ฐํ๋ ๊ฒฝ์ฐ๋ฅผ push, ๋นผ๋ ๊ฒฝ์ฐ๋ฅผ pop ์ด๋ผ ํฉ๋๋ค. stack์ ํน์ง์ LIFO ๋ก ๋ฐ์ดํฐ๊ฐ ๊ด๋ฆฌ๋ฉ๋๋ค.
LIFO - Last In First Out
LIFO๋ CS๋ฟ๋ง ์๋๋ผ ๋ค์ํ ๋ถ์ผ์์๋ ์ฌ์ฉ๋๋ ์ฉ์ด์ด์ฃ ! ๊ทธ ๋ด์ฉ๊ณผ ๋๊ฐ์ต๋๋ค. ์๋ฅผ ๋ค๋ฉด, ๊ตฌ๋งค ๊ด๋ฆฌ๋ฅผ ํ๋๋ฐ ์์ด์, ์ต๊ทผ ์์๋ ์์ฐํ์ด ๋ถ๋ํ์ด ๋ฐ์ ํ๋ค๊ณ ๊ฐ์ ํด๋ณด์ฃ . ๊ทธ๋ฌ๋ฉด ์ฐ๋ฆฌ๋ ์ง์ด๋ ์ํ์ค ์ต๊ทผ์ ์ง์ด๋ ์ํ๋ถํฐ ํ๋์ฉ ์ ๊ฑฐํด์ผํฉ๋๋ค. ์ฆ, LIFO๋ ์ฐ๋ฆฌ๋ง๋ก ํ์ ์ ์ถ์ด๋ผ๊ณ ํฉ๋๋ค.
Stack by Swift
์ ๋ค๋ฆญ์ ์ฌ์ฉํด์ ์ด๋ค ํ์ ๋ ๋ค์ด์ฌ ์ ์๊ฒ ํด์ ์์ฑํ๋ฉด ๋ฉ๋๋ค. ๊ทธ๋ฅ Array๋ฅผ stack์ฒ๋ผ ์ฌ์ฉํด๋ ๋ฌด๋ฐฉํ ๊ฒ์ด๋ผ ์๊ฐ ๋์ง๋ง, ํ๋ฒ ์ฝ๋๋ก ์์ฑํด ๋ณด์์ต๋๋ค.
struct Stack<T> {
private var stack = [T]()
public var isEmpty: Bool {
return stack.isEmpty
}
public mutating func push(_ element: T) {
stack.append(element)
}
public mutating func pop() -> T? {
return isEmpty ? nil : stack.popLast()
}
}
Queue๋ ์์ Stack๊ณผ ๋ฐ๋๋๋ ๊ตฌ์กฐ๋ก, ์์ํ๋ฏ์ด FIFO๋ก ๋ฐ์ดํฐ๊ฐ ๊ด๋ฆฌ๋ฉ๋๋ค.
FIFO - First In First Out
FIFO๋ ์ง์ด๋ ์ํ ์ค ์ํต๊ธฐํ์ ๊ด๋ฆฌํ๋ค๊ณ ์๊ฐํ๋ฉด ๋ฉ๋๋ค. ์ ํต๊ธฐํ์ด ์ง๋ ์ํ์ ์ง์ด์์ ์ ๊ฑฐํ๊ธฐ ์ํด์๋ ๊ฐ์ฅ ๋จผ์ ์ง์ด๋ ์ํ๋ถํฐ ์ ๊ฑฐํด์ผ๊ฒ ์ฃ ! ์ฆ, FIFO๋ ์ฐ๋ฆฌ๋ง๋ก ์ ์ ์ ์ถ์ด๋ผ๊ณ ํฉ๋๋ค.
Queue by Swift
์ ๋ค๋ฆญ์ ์ฌ์ฉํด์ ์ด๋ค ํ์ ๋ ๋ค์ด์ฌ ์ ์๊ฒ ํด์ ์์ฑํ๋ฉด ๋ฉ๋๋ค.
struct Queue<T> {
private var queue = [T]()
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()
}
}