연결 목록에서 특정 요소 집합을 반전해야 하는 경우 'reverse_list'라는 메서드가 정의됩니다. 이것은 목록을 반복하고 특정 요소 집합을 뒤집습니다.
아래는 동일한 데모입니다 -
예시
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_it(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
def reverse_list(my_list, n):
if n == 0:
return
before_val = None
curr = my_list.head
if curr is None:
return
after_val = curr.next
for i in range(n):
curr.next = before_val
before_val = curr
curr = after_val
if after_val is None:
break
after_val = after_val.next
my_list.head.next = curr
my_list.head = before_val
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))
n = int(input('Enter the number of elements you wish to reverse in the list... '))
reverse_list(my_instance, n)
print('The new list is : ')
my_instance.print_it() 출력
Enter the elements of the linked list... 45 67 89 12 345 Enter the number of elements you wish to reverse in the list... 3 The new list is : 89 67 45 12 345
설명
-
'Node' 클래스가 생성됩니다.
-
필수 속성이 있는 또 다른 'LinkedList_structure' 클래스가 생성됩니다.
-
첫 번째 요소, 즉 'head'를 'None'으로 초기화하는 데 사용되는 'init' 기능이 있습니다.
-
스택에 값을 추가하는 데 도움이 되는 'add_vals'라는 메서드가 정의되어 있습니다.
-
콘솔에 연결된 목록의 값을 표시하는 데 도움이 되는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
-
'reverse_list'라는 또 다른 메서드가 정의되어 연결 목록의 특정 요소 집합을 뒤집는 데 도움이 됩니다.
-
LinkedList_structure'의 인스턴스가 생성됩니다.
-
연결 목록에 요소가 추가됩니다.
-
요소가 콘솔에 표시됩니다.
-
되돌려야 하는 요소의 수는 사용자로부터 가져옵니다.
-
이 연결 리스트에서 'reverse_list' 메소드가 호출됩니다.
-
출력은 콘솔에 표시됩니다.