연결 리스트의 가장 가운데에 있는 요소를 출력해야 하는 경우 'print_middle_val'이라는 메서드를 정의합니다. 이 메서드는 연결 목록을 매개 변수로 사용하고 가장 가운데에 있는 요소를 가져옵니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_structure:
def __init__(self):
self.head = None
self.last_node = None
def add_vals(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 print_middle_val(my_list):
curr = my_list.head
my_len = 0
while curr:
curr = curr.next
my_len = my_len + 1
curr = my_list.head
for i in range((my_len - 1)//2):
curr = curr.next
if curr:
if my_len % 2 == 0:
print('The two middle elements are {} and {}'.format(curr.data, curr.next.data))
else:
print('The middle-most element is {}.'.format(curr.data))
else:
print('The list is empty')
my_instance = LinkedList_structure()
my_list = input('Enter the elements of the linked list... ').split()
for elem in my_list:
my_instance.add_vals(int(elem))
print_middle_val(my_instance) 출력
Enter the elements of the linked list... 56 23 78 99 34 11 The two middle elements are 78 and 99
설명
-
'Node' 클래스가 생성됩니다.
-
필수 속성이 있는 또 다른 'LinkedList_structure' 클래스가 생성됩니다.
-
첫 번째 요소, 즉 'head'를 'None'으로 초기화하는 데 사용되는 'init' 기능이 있습니다.
-
스택에 값을 추가하는 데 도움이 되는 'add_vals'라는 메서드가 정의되어 있습니다.
-
콘솔에 연결 목록의 중간 값을 표시하는 데 도움이 되는 'print_middle_val'이라는 또 다른 메서드가 정의되어 있습니다.
-
LinkedList_structure'의 인스턴스가 생성됩니다.
-
연결 목록에 요소가 추가됩니다.
-
요소가 콘솔에 표시됩니다.
-
이 연결 리스트에서 'print_middle_val' 메소드가 호출됩니다.
-
출력은 콘솔에 표시됩니다.