우선 리스트를 큐처럼 활용해보았다.
# 1. 리스트를 큐처럼 활용하기
queue = []
queue.append(1)
queue.append(2)
queue.append(3)
first_item = queue.pop(0) # 인덱스 0번 출력
print(first_item) # 출력 : 1
queue.append(4)
queue.append(5)
first_item = queue.pop(0)
print(first_item) # 출력 : 2
다음으론 시간복잡도를 낮추기 위하여 파이썬의 collections모듈의 데크를 가져와 큐를 구현해보았다.
#2. 덱을 큐처럼 활용하기 - 시간복잡도 낮음
from collections import deque
que = deque()
que.append(1)
que.append(2)
que.append(3) # deque([1, 2, 3])
first_item = que.popleft()
print(first_item) # 1
que.append(4)
que.append(5)
first_item = que.popleft()
print(first_item) # 2
확실히 파이썬은 다른 언어에 비해 뭔가를 구현하기 참 쉬운 언어인 것 같다.
'PS' 카테고리의 다른 글
| 이중 연결리스트 구현(python) (1) | 2025.08.16 |
|---|---|
| 연결리스트 구현(python) (3) | 2025.08.16 |