이중 연결 목록의 시작 부분에 새 노드를 삽입해야 하는 경우 '노드' 클래스를 생성해야 합니다. 이 클래스에는 노드에 있는 데이터, 연결 목록의 다음 노드에 대한 액세스, 연결 목록의 이전 노드에 대한 액세스의 세 가지 속성이 있습니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
class double_list:
def __init__(self):
self.head = None
self.tail = None
def add_data_at_start(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.previous = new_node
new_node.next = self.head
new_node.previous = None
self.head = new_node
def print_it(self):
curr = self.head
if (self.head == None):
print("The list is empty")
return
print("The nodes in the doubly linked list are :")
while curr != None:
print(curr.data)
curr = curr.next
my_instance = double_list()
print("Elements are being added to the beginning of doubly linked list")
my_instance.add_data_at_start(10)
my_instance.print_it()
my_instance.add_data_at_start(24)
my_instance.print_it()
my_instance.add_data_at_start(54)
my_instance.print_it()
my_instance.add_data_at_start(77)
my_instance.print_it()
my_instance.add_data_at_start(92)
my_instance.print_it() 출력
Elements are being added to the beginning of doubly linked list The nodes in the doubly linked list are : 10 The nodes in the doubly linked list are : 24 10 The nodes in the doubly linked list are : 54 24 10 The nodes in the doubly linked list are : 77 54 24 10 The nodes in the doubly linked list are : 92 77 54 24 10입니다.
설명
- '노드' 클래스가 생성됩니다.
- 필수 속성이 있는 다른 클래스가 생성됩니다.
- 이중 연결 목록의 시작 부분에 데이터를 추가하는 데 사용되는 'add_data_at_start'라는 메서드가 정의되어 있습니다.
- 순환 연결 목록의 노드를 표시하는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
- 'double_list' 클래스의 객체가 생성되고 이중 연결 리스트의 시작 부분에 데이터를 추가하기 위해 메서드가 호출됩니다.
- 이중 연결 리스트의 루트, 헤드, 테일 노드를 None으로 하는 'init' 메소드가 정의되어 있습니다.
- 목록이 반복되고 요소가 이중 연결 목록의 시작 부분에 추가됩니다.
- 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.