Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

재귀 함수를 사용해 연결 리스트의 대체 노드를 출력하는 Python 프로그램

연결 리스트(linked list)에서 재귀(recursion)를 활용해 대체 노드, 즉 한 칸씩 건너뛴 위치의 노드들을 출력해야 하는 경우가 있습니다. 이를 구현하려면 연결 리스트에 요소를 추가하는 메서드, 리스트 전체를 화면에 표시하는 메서드, 그리고 대체 값을 추출하는 메서드를 각각 정의해야 합니다. 여기에 더해, 앞서 정의한 메서드를 호출해 대체 값을 실제로 얻어내는 별도의 헬퍼(helper) 함수도 함께 사용합니다.

아래는 이를 구현한 예제입니다.

예제 코드

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

class my_linked_list:
    def __init__(self):
        self.head = None
        self.last_node = None

    def add_value(self, my_data):
        if self.last_node is None:
            self.head = Node(my_data)
            self.last_node = self.head
        else:
            self.last_node.next = Node(my_data)
            self.last_node = self.last_node.next

    def print_it(self):
        curr = self.head
        while curr:
            print(curr.data)
            curr = curr.next

    def alternate_nodes(self):
        self.alternate_helper_fun(self.head)

    def alternate_helper_fun(self, curr):
        if curr is None:
            return
        print(curr.data, end = ' ')
        if curr.next:
            self.alternate_helper_fun(curr.next.next)

my_instance = my_linked_list()
my_list = input("Enter the elements of the linked list :").split()
for elem in my_list:
    my_instance.add_value(elem)
print("The alternate elements in the linked list are :")
my_instance.alternate_nodes()

실행 결과

Enter the elements of the linked list :78 56 34 52 71 96 0 80
The alternate elements in the linked list are :
78 34 71 0

코드 설명

  • 노드 하나를 나타내는 'Node' 클래스가 생성됩니다.

  • 필요한 속성을 갖춘 'my_linked_list' 클래스가 정의됩니다.

  • '__init__' 함수는 첫 번째 요소인 'head'와 마지막 노드를 가리키는 'last_node'를 모두 'None'으로 초기화합니다.

  • 'add_value' 메서드는 연결 리스트 끝에 새 데이터를 추가하는 역할을 합니다.

  • 'print_it' 메서드는 리스트를 처음부터 끝까지 순회하며 모든 요소를 출력합니다.

  • 'alternate_nodes' 메서드는 헬퍼 함수를 호출하는 진입점 역할을 합니다.

  • 'alternate_helper_fun' 헬퍼 함수는 연결 리스트를 순회하면서 한 칸씩 건너뛴 위치의 요소들만 화면에 표시합니다.

  • 이 함수는 재귀 함수이므로 자기 자신을 계속 호출하며 동작합니다. 핵심은 curr.next.next로 두 칸씩 이동해 중간 노드를 건너뛰는 부분입니다.

  • 리스트가 끝나면(None에 도달하면) 재귀 호출이 종료되어 안전하게 탈출합니다.

  • 'my_linked_list' 클래스의 객체가 생성되고, 사용자 입력값이 연결 리스트에 차례대로 추가됩니다.

  • 'alternate_nodes' 메서드를 호출하면 대체 노드들이 출력되며, 그 결과가 콘솔에 표시됩니다.