단일 연결 목록을 순환 연결 목록으로 변환해야 하는 경우 마지막 요소가 첫 번째 요소를 가리키도록 하여 본질적으로 원형이 되도록 하는 '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...
설명
-
'노드' 클래스가 생성됩니다.
-
필수 속성이 있는 또 다른 'LinkedList_struct' 클래스가 생성됩니다.
-
첫 번째 요소, 즉 'head'를 'None'으로, 마지막 노드를 'None'으로 초기화하는 데 사용되는 'init' 기능이 있습니다.
-
링크드 리스트에서 이전 노드를 가져오는 데 사용되는 'add_elements'라는 또 다른 메서드가 정의되어 있습니다.
-
마지막 노드가 첫 번째 노드를 가리키도록 하는 'convert_to_circular_list'라는 또 다른 메서드가 정의되어 본질적으로 순환합니다.
-
목록이 비어 있는지, 마지막 노드가 'None'을 가리키는지, 연결 목록의 특정 노드를 가리키는지 확인하는 'last_node_points'라는 메서드가 정의되어 있습니다.
-
LinkedList_struct' 클래스의 객체가 생성됩니다.
-
연결 목록의 요소에 대한 사용자 입력을 받습니다.
-
연결 목록에 요소가 추가됩니다.
-
이 연결 리스트에서 'last_node_points' 메소드가 호출됩니다.
-
관련 출력이 콘솔에 표시됩니다.