이중 연결 목록을 생성하고 요소를 역순으로 표시해야 하는 경우 '노드' 클래스를 생성해야 합니다. 이 클래스에는 노드에 있는 데이터, 연결 목록의 다음 노드에 대한 액세스, 연결 목록의 이전 노드에 대한 액세스의 세 가지 속성이 있습니다.
초기화 기능이 있는 다른 클래스를 생성해야 하며, 이 안에서 노드의 헤드는 'None'으로 초기화됩니다.
연결 목록에 노드를 추가하고, 노드를 역전시키고 연결 목록의 노드를 인쇄하기 위해 사용자가 여러 가지 방법을 정의합니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
class reverse_list:
def __init__(self):
self.head = None
self.tail = None
def add_data(self, my_data):
new_node = Node(my_data)
if(self.head == None):
self.head = self.tail = new_node;
self.head.previous = None;
self.tail.next = None;
else:
self.tail.next = new_node;
new_node.previous = self.tail;
self.tail = new_node;
self.tail.next = None;
def reverse_vals(self):
curr = self.head;
while(curr != None):
temp = curr.next
curr.next = curr.previous
curr.previous = temp
curr = curr.previous
temp = self.head
self.head = self.tail
self.tail = temp
def print_it(self):
curr = self.head
if (self.head == None):
print("The list is empty")
return
print("The nodes are :")
while curr != None:
print(curr.data)
curr = curr.next
my_instance = reverse_list()
print("Elements are being added to the list")
my_instance.add_data(10)
my_instance.add_data(14)
my_instance.add_data(24)
my_instance.add_data(17)
my_instance.add_data(22)
my_instance.print_it()
print("The reversed nodes in the doubly linked list are : ")
my_instance.reverse_vals()
my_instance.print_it() 출력
Elements are being added to the list The nodes are : 10 14 24 17 22 The reversed nodes in the doubly linked list are : The nodes are : 22 17 24 14 10
설명
- '노드' 클래스가 생성됩니다.
- 필수 속성이 있는 다른 클래스가 생성됩니다.
- 이중 연결 목록에 데이터를 추가하는 데 사용되는 'add_data'라는 메서드가 정의되어 있습니다.
- 이중 연결 목록에서 노드의 순서를 반대로 하는 데 도움이 되는 'reverse_node'라는 또 다른 메서드가 정의되어 있습니다.
- 순환 연결 목록의 노드를 표시하는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
- 'reverse_list' 클래스의 객체가 생성되고 이중 연결 리스트의 노드를 반전시키기 위해 메소드가 호출됩니다.
- 이중 연결 리스트의 루트, 헤드, 테일 노드를 None으로 하는 'init' 메소드가 정의되어 있습니다.
- 'reverse_vals' 메소드가 호출됩니다.
- 이중 연결 목록을 반복하고 목록을 뒤집습니다.
- 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.