🔻Language/Python

[Python] LinkList 구현하기

_니지 2024. 11. 4. 19:40

❗LinkList 이론

https://radiant515.tistory.com/730

 

[DS] LinkedList

❗LinkedList란?LinkedList란 각 데이터 요소가 노드 형태로 존재하고 각 노드가 다음 노드를 가리키며 연결된 형태를 가진다. 연결 구조 덕분에 데이터의 삽입과 삭제가 유연하게 가능하여 이 점에서

radiant515.tistory.com

 

 

❗Python에서 LinkList 구현하기

1. 딕셔너리 구현

# 연결 리스트를 나타내는 딕셔너리와 head 노드를 정의
linked_list = {}
head = None

# 노드 추가 함수
def append(key, data):
    global head
    # 새 노드 추가
    linked_list[key] = {"data": data, "next": None}
    
    # 리스트가 비어 있을 경우 첫 노드를 head로 설정
    if head is None:
        head = key
    else:
        # 마지막 노드를 찾아 새 노드를 연결
        current_key = head
        while linked_list[current_key]["next"] is not None:
            current_key = linked_list[current_key]["next"]
        linked_list[current_key]["next"] = key

# 리스트 출력 함수
def print_list():
    current_key = head
    while current_key is not None:
        print(linked_list[current_key]["data"], end=" -> ")
        current_key = linked_list[current_key]["next"]
    print("None")

# 사용 예제
append("node1", "Apple")
append("node2", "Banana")
append("node3", "Cherry")
print_list()  # Apple -> Banana -> Cherry -> None

 

 

2. 클래스 구현

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

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

    def print_list(self):
        current_node = self.head
        while current_node:
            print(current_node.data, end=" -> ")
            current_node = current_node.next
        print("None")

# 사용 예제
ll = LinkedList()
ll.append("Apple")
ll.append("Banana")
ll.append("Cherry")
ll.print_list()  # Apple -> Banana -> Cherry -> None

 

 

 

728x90
반응형