Python 자료구조 1. stack & queue (with list)

이형래·2021년 8월 24일
2

Python

목록 보기
1/10
post-thumbnail

Python 자료구조

1. stack & queue (리스트로 구현하기)

1.1 스택 - stack (with list)

  • 나중에 넣은 데이터를 먼저 반환하는 메모리 구조.
  • Last In First out (LIFO)
  • data 입력을 push, 출력을 pop이라고 한다.

스택
<출처 : 위키백과>

  • list를 사용하여 스택 구조를 구현할 수 있다.
  • append()push 기능
  • pop()pop 기능
list_a = [1, 2, 3, 4, 5]
print(f"list_a : {list_a}")
list_a.append(6)			# 맨 뒤에 6을 push
print(f"list_a : {list_a}")
list_a.pop()				# 맨 뒤에 있는 요소를 꺼냄
print(f"list_a : {list_a}")
list_a.pop()				# 맨 뒤에 있는 요소를 꺼냄
print(f"list_a : {list_a}")

1.2 큐 - queue (with list)

  • 먼저 넣은 데이터를 먼저 반환하는 메모리 구조.

  • First In First Out (FIFO)

  • list를 사용하여 스택 구조를 구현할 수 있다.

  • append()push 기능

  • pop(0)pop 기능

list_a = [1, 2, 3, 4, 5]
print(f"list_a : {list_a}")
list_a.append(6)			# 맨 뒤에 6을 push
print(f"list_a : {list_a}")
list_a.pop(0)				# 맨 앞에 있는 요소를 꺼냄
print(f"list_a : {list_a}")
list_a.pop(0)				# 맨 앞에 있는 요소를 꺼냄
print(f"list_a : {list_a}")

유사하게 del을 이용해서 값을 없앨수도 있다.

list_a = [1, 2, 3, 4, 5]
print(f"list_a : {list_a}")
list_a.append(6)
print(f"list_a : {list_a}")
del list_a[0]
print(f"list_a : {list_a}")
del list_a[0]
print(f"list_a : {list_a}")
profile
머신러닝을 공부하고 있습니다. 특히 비전 분야에 관심이 많습니다.

0개의 댓글