Computer Science/Algorithm

[Algorithm] 파이썬에서 스택(Stack)과 큐(Queue)의 사용

728x90

 

 

스택 (Stack)

- 선입후출(First-In Last-Out) 구조 또는 후입선출 구조

- 박스 쌓기에 비유할 수 있다

 

🔥 스택 with Python

- 별도의 라이브러리 없이 기본 리스트에서 append(), pop() 메서드를 이용하여 사용 가능하다

stack = []

stack.append(5)
stack.append(2)
stack.append(3)
stack.pop()	# 3
stack.append(1)
stack.append(4)
stack.pop()	# 4

print(stack[::-1])
# 최상단 원소부터 출력
# [1, 2, 5]

 

 

 

큐 (Queue)

- 선입선출(First-In First-Out) 구조

- 대기 줄에 비유할 수 있는 '공정한' 자료구조라고 할 수 있다

 

🔥 큐 with Python

- collections 모듈의 deque 자료구조를 활용하다

- deque 객체를 리스트로 변경할 때는 list()로 감싼다

from collections import deque

queue = deque()

queue.append(5)
queue.append(2)
queue.append(3)
queue.popleft()	# 5
queue.append(1)
queue.append(4)
queue.popleft()	# 2

print(list(queue))
# [3, 1, 4]

 

 

 

 

 

 

 

📚 참고서적 : 이것이 코딩테스트다 with 파이썬

 

728x90