📝오늘 공부한 것
- 프로그래머스 문제풀기
- 스파르타코딩클럽 자료구조 & 알고리즘 1주차 강의 듣기
알게 된 점❗
[ 연결 리스트 ]
Array & LinkedList
Array | LinkedList | |
특정 원소 조회 | O(1) | O(N) |
중간에 삽입 삭제 | O(N) | O(1) |
데이터 추가 | 데이터 추가 시 모든 공간이 다 차버렸다면 새로운 메모리 공간을 할당받아야 한다 | 모든 공간이 다 찼어도 맨 뒤의 노드만 동적으로 추가하면 된다. |
정리 | 데이터에 접근하는 경우가 빈번하다면 Array를 사용하자 | 삽입과 삭제가 빈번하다면 LinkedList를 사용하는 것이 더 좋다. |
연결리스트의 구현
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def append(self, val):
if not self.head:
self.head = ListNode(val, None)
return
node = self.head
while node.next:
node = node.next
node.next = ListNode(val, None)
[ 스택 ]
Last In First Out의 자료 구조
ex) 컴퓨터의 되돌리기(Ctrl + Z) 기능
def test_node():
assert Node(1, None).item == 1
def test_stack():
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
assert stack.pop() == 5
assert stack.pop() == 4
assert stack.pop() == 3
assert stack.pop() == 2
assert stack.pop() == 1
assert stack.pop() is None
assert stack.is_empty()
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class Stack:
def __init__(self):
self.top = None
def push(self, value):
self.top = Node(value, self.top)
def pop(self):
if self.top is None:
return None
node = self.top
self.top = self.top.next
return node.item
def is_empty(self):
return self.top is None
[ 큐 ]
First In First Out의 자료 구조
ex) 주문이 들어왔을 때 먼저 들어온 순서대로 처리해야 할 때, 먼저 해야하는 일들을 저장하고 싶을 때 등
def test_queue():
queue = Queue()
queue.push(1)
queue.push(2)
queue.push(3)
queue.push(4)
queue.push(5)
assert queue.pop() == 1
assert queue.pop() == 2
assert queue.pop() == 3
assert queue.pop() == 4
assert queue.pop() == 5
assert queue.pop() is None
assert queue.is_empty()
class Queue:
def __init__(self):
self.front = None
def push(self, value):
if not self.front:
self.front = Node(value, None)
return
node = self.front
while node.next:
node = node.next
node.next = Node(value, None)
def pop(self):
if not self.front:
return None
node = self.front
self.front = self.front.next
return node.item
def is_empty(self):
return self.front is None
오늘을 자료구조에서 스택과 큐에 대해서 배웠는데 자바 공부할 때 나온 개념이라 이해하기 쉬웠지만, 스택과 큐를 코드로 구현할 수 있어야 된다는 건 오늘 처음 알았다..
강의가 파이썬으로 진행되어서 중간중간 이해가지 않는 코드들이 있었다. 자바로 코드를 작성하면서 다시한번 공부해야겠다!!
'TIL(Today I Learned)' 카테고리의 다른 글
TIL-231003(자료구조 & 알고리즘 2주차) (0) | 2023.10.03 |
---|---|
TIL-231002(자료구조 & 알고리즘 2주차) (0) | 2023.10.02 |
TIL-230929(자료구조 & 알고리즘 1주차) (0) | 2023.09.29 |
TIL-230928(자료구조 & 알고리즘 1주차) (0) | 2023.09.28 |
TIL-230927(자바의정석 Chapter10 '날짜와 시간 & 형식화') (0) | 2023.09.27 |