728x90
์คํ(Stack)
- ๋์ค์ ๋ฃ์ ๋ฐ์ดํฐ๋ฅผ ๋จผ์ ๋นผ๋ ํ์ ์ ์ถ(LIFO - Last In First Out) ๊ตฌ์กฐ
- ex) ๋ฐ์ค ์๊ธฐ, ํธ๋ญ์ ๋ฌผ๊ฑด ๋ฃ๊ธฐ
- ํ์ด์ฌ ๊ธฐ๋ณธ ๋ฆฌ์คํธ์์ append()์ pop() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํ
stack = []
stack.append(1) # stack: [1]
stack.append(2) # stack: [1, 2]
stack.append(3) # stack: [1, 2, 3]
stack.append(4) # stack: [1, 2, 3, 4]
stack.pop() # stack: [1, 2, 3]
stack.pop() # stack: [1, 2]
stack.append(3) # stack: [1, 2, 3]
stack.pop() # stack: [1, 2]
ํ(Queue)
- ๋จผ์ ๋ฃ์ ๋ฐ์ดํฐ๋ฅผ ๋จผ์ ๋นผ๋ ์ ์ ์ ์ถ(FIFO - First In First Out) ๊ตฌ์กฐ
- ex) ์ ์ฅ ๋๊ธฐ์ค
- ํ์ด์ฌ collections ๋ชจ๋์์ ์ ๊ณตํ๋ deque ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํ
โป deque๋ ์คํ๊ณผ ํ์ ์ฅ์ ์ ๋ชจ๋ ์ฑํํ ์๋ฃ๊ตฌ์กฐ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ฃ๊ณ ๋นผ๋ ์๋๊ฐ ๋ฆฌ์คํธ ์๋ฃํ์ ๋นํด ํจ์จ์ ์ด๋ฉฐ queue ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค ๊ฐ๋จํ๋ค.
from collections import deque
queue = deque()
queue.append(1) # queue: [1]
queue.append(2) # queue: [1, 2]
queue.append(3) # queue: [1, 2, 3]
queue.append(4) # queue: [1, 2, 3, 4]
queue.popleft() # queue: [2, 3, 4]
queue.popleft() # queue: [3, 4]
queue.append(5) # queue: [3, 4, 5]
queue.popleft() # queue: [4, 5]
728x90