[Python] LinkedList 구현

2025. 3. 25. 20:31
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


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

    def append(self, value):
        cur = self.head
        while cur.next is not None:
            cur = cur.next
        cur.next = Node(value)

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

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

        while cur_index != index:
            cur = cur.next
            cur_index += 1
        return cur

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

        if index == 0:
            next_node = self.head

            self.head = new_node
            self.head.next = next_node

            return

        prev_node = self.get_node(index-1)
        next_node = prev_node.next

        prev_node.next = new_node
        new_node.next = next_node

    def delete_node(self, index):
        print("index 번째 노드를 삭제해주세요")

        if index == 0:
            self.head = self.get_node(1)
            return

        # 삭제할 index의 노드에 도착
        next_node = self.get_node(index+1)
        prev_node = self.get_node(index-1)
        prev_node.next = next_node

BELATED ARTICLES

more