연결리스트

Yunes·2023년 10월 25일
0
post-thumbnail

유용할 연결 리스트 기법 정리

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

아래의 함수들은 class LinkedList 내의 메서드이다.

새 노드 추가

# 새로운 노드 추가
def append(self, data):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
    else:
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

모든 노드 값 출력

# 모든 노드 값 출력
def display(self):
    current = self.head
    while current:
        print(current.data, end=" -> ")
        current = current.next
    print("None")

노드 삽입

# 노드 삽입
def insert(self, data, position):
    new_node = Node(data)
    if position == 0:
        new_node.next = self.head
        self.head = new_node
    else:
        current = self.head
        count = 0
        while current and count < position - 1:
            current = current.next
            count += 1
        if current is None:
            print("지정된 위치에 노드를 삽입할 수 없습니다.")
        else:
            new_node.next = current.next
            current.next = new_node

노드 삭제

# 노드 삭제
def delete(self, data):
    current = self.head
    if current and current.data == data:
        self.head = current.next
        return
    while current:
        if current.next and current.next.data == data:
            current.next = current.next.next
            return
        current = current.next

활용 코드

# 연결 리스트 테스트
if __name__ == "__main__":
    linked_list = LinkedList()
    
    linked_list.append(1)
    linked_list.append(2)
    linked_list.append(3)
    linked_list.append(4)

    print("모든 노드 값 출력:")
    linked_list.display()
    
    linked_list.insert(5, 2)
    print("노드 삽입 후:")
    linked_list.display()
    
    linked_list.delete(3)
    print("노드 삭제 후:")
    linked_list.display()
profile
미래의 나를 만들어나가는 한 개발자의 블로그입니다.

0개의 댓글