Node 구현

  • 보통 파이썬에서 링크드 리스트 구현시, 파이썬 클래스를 활용

링크드 리스트의 장단점(전통적인 C언어에서의 배열과 링크드 리스트)

  1. 장점
  • 데이터 공간을 미리 할당하지 않아도 된다.
  • (배열은 미리 데이터 공간을 할당해야 한다)
  1. 단점
  • 연결을 위한 별도 데이터 공간이 필요하므로,저장공간 효율이 높지 않다.
  • 연결 정보를 찾는 시간이 필요하므로 접근 속도가 느리다.
  • 중간 데이터 삭제시, 앞뒤 데이터의 연결을 재구성해야 하는 부가적인 작업 필요하다.

5.파이썬 객체지향 프로그래밍으로 링크드 리스트 구현하기

class Node:   //Node Class는 Linked List의 각 요소를 나타낸다.
//Node Class에서는 Data를 저장하는 data속성과 다음 Node를 참조하는 next 속성을 가지고 있다.
    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 self.head is None:
            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")

# 사용 예제
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.print_list()

+ Recent posts