내배캠 11일차

·2022년 11월 24일
0

내일배움캠프

목록 보기
10/142
post-thumbnail

링크드리스트

-노드는 아래 두 가지 정보가 필요
1) 칸에 있는 데이터
2) 다음 칸이 뭔지
=> 클래스를 이용해 생성

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        
first_node = Node(5) # 현재는 next 가 없이 하나의 노드만 [5]
second_node = Node(12) # [12] 를 들고 있는 노드를 생성
first_node.next = second_node # 그리고, [5]의 next 를 [12]로 지정[5] -> [12]

=>이런식으로 일일이 연결해주는것은 너무 번거로움.
따라서 LinkedList 라는 클래스를 생성(head node만 들고있는)
1) LinkdList 는 self.head 에 시작하는 노드를 저장한다.
2) 다음 노드를 보기 위해서는 각 노드의 next 를 조회해서 찾아가야 한다.

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self, data):
        self.head = Node(data)

    def append(self, data):
        if self.head is None:
            self.head = Node(data)
            return

        cur = self.head
        while cur.next is not None:
            cur = cur.next
        cur.next = Node(data)

    def print_all(self):
        cur = self.head
        while cur is not None:
            print(cur.data)
            cur = cur.next


linked_list = LinkedList(3)

linked_list.append(4)
linked_list.append(5)
linked_list.print_all()

링크드리스트 원소 찾기

    def get_node(self, index):
        cur = self.head
        count = 0

        while cur is not None:
            if index == count:
                return print(cur.data)

            cur = cur.next
            count += 1

=>예외처리하는 코드를 짜보기

링크드리스트 인덱스에 추가하기

    def add_node(self, index, value):
        new_node = Node(value)

        if index == 0:
            new_node.next = self.head
            self.head = new_node

        node_1 = self.get_node(index-1)
        node_2 = self.get_node(index)
        node_1.next = new_node
        new_node.next = node_2

=>복잡하게 생각하지말고 앞에서 짠 get_node를 이용하면 쉽다!

profile
개발자 꿈나무

0개의 댓글