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
'Computer Science > Algorithm' 카테고리의 다른 글
[Algorithm] 정렬 (Sorting) : 선택 정렬, 삽입 정렬, 퀵 정렬, 계수 정렬 파이썬 정렬 라이브러리 예제 코드 및 시간 복잡도 (0) | 2021.09.04 |
---|---|
[Algorithm] DFS (깊이 우선 탐색) / BFS (너비 우선 탐색) : 파이썬 예제 코드 + 인접 행렬, 인접 리스트 (0) | 2021.09.01 |
[Algorithm] 리스트 컴프리헨션 (List Comprehension) (0) | 2021.09.01 |
[Algorithm] 구현 문제 (Implementation) with 방향 이동(dx, dy) (0) | 2021.09.01 |
[Algorithm] 그리디 알고리즘 (Greedy Algorithm), 탐욕법 (0) | 2021.09.01 |