단일 연결 리스트(singly linked list)를 순환 연결 리스트(circular linked list)로 변환해야 하는 경우가 있습니다. 이때는 convert_to_circular_list라는 메서드를 정의하여 마지막 노드가 첫 번째 노드를 가리키도록 함으로써 리스트 전체가 원형 구조를 갖도록 만들 수 있습니다.
아래 예제를 통해 그 과정을 살펴보겠습니다.
예제 코드
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_struct:
def __init__(self):
self.head = None
self.last_node = None
def add_elements(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def convert_to_circular_list(my_list):
if my_list.last_node:
my_list.last_node.next = my_list.head
def last_node_points(my_list):
last = my_list.last_node
if last is None:
print('The list is empty...')
return
if last.next is None:
print('The last node points to None...')
else:
print('The last node points to element that has {}...'.format(last.next.data))
my_instance = LinkedList_struct()
my_input = input('Enter the elements of the linked list.. ').split()
for data in my_input:
my_instance.add_elements(int(data))
last_node_points(my_instance)
print('The linked list is being converted to a circular linked list...')
convert_to_circular_list(my_instance)
last_node_points(my_instance)실행 결과
Enter the elements of the linked list.. 56 32 11 45 90 87 The last node points to None... The linked list is being converted to a circular linked list... The last node points to element that has 56...
코드 설명
먼저 노드를 표현하는
Node클래스를 생성합니다.필요한 속성들을 담고 있는
LinkedList_struct클래스를 정의합니다.__init__함수는 첫 번째 요소인head와 마지막 노드인last_node를 모두None으로 초기화하는 역할을 합니다.add_elements메서드는 새로운 데이터를 연결 리스트의 끝에 추가하는 기능을 수행합니다.convert_to_circular_list메서드는 마지막 노드가 첫 번째 노드를 가리키도록 설정하여 리스트를 순환 구조로 만듭니다.last_node_points메서드는 리스트가 비어 있는지, 마지막 노드가None을 가리키는지, 아니면 특정 노드를 가리키는지 확인하여 결과를 출력합니다.LinkedList_struct클래스의 객체(인스턴스)를 생성합니다.사용자로부터 연결 리스트에 넣을 요소들을 입력받습니다.
입력받은 요소들을 하나씩 연결 리스트에 추가합니다.
변환 전에
last_node_points메서드를 호출하여 마지막 노드의 상태를 확인합니다.convert_to_circular_list를 호출한 뒤 다시 상태를 확인하면, 마지막 노드가 첫 번째 요소(56)를 가리키는 것을 콘솔에서 확인할 수 있습니다.