이중 연결 리스트 중간에 새로운 노드를 삽입해야 하는 경우에는 'Node' 클래스를 생성해야 합니다. 이 클래스에는 노드에 있는 데이터, 연결 목록의 다음 노드에 대한 액세스, 연결 목록의 이전 노드에 대한 액세스의 세 가지 속성이 있습니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self, my_data):
self.previous = None
self.data = my_data
self.next = None
class double_list:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
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
self.size = self.size + 1
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
def add_data_in_middle(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:
curr = self.head;
mid = (self.size//2) if(self.size % 2 == 0) else ((self.size+1)//2);
for i in range(1, mid):
curr = curr.next;
temp = curr.next;
temp.previous = curr;
curr.next = new_node;
new_node.previous = curr;
new_node.next = temp;
temp.previous = new_node;
self.size = self.size + 1;
my_instance = double_list()
print("Elements are being added to the doubly linked list")
my_instance.add_data(10)
my_instance.add_data(24)
my_instance.add_data(54)
print("Elements are added to the middle of the list")
my_instance.add_data_in_middle(77)
my_instance.print_it()
my_instance.add_data_in_middle(92)
my_instance.print_it() 출력
Elements are being added to the doubly linked list Elements are added to the middle of the list The nodes in the doubly linked list are : 10 24 77 54 The nodes in the doubly linked list are : 10 24 92 77 54
설명
- '노드' 클래스가 생성됩니다.
- 필수 속성이 있는 다른 클래스가 생성됩니다.
- 이중 연결 목록의 중간 인덱스에 데이터를 추가하는 데 사용되는 'add_data_in_middle'이라는 메서드가 정의되어 있습니다.
- 이중 연결 목록에 노드를 추가하는 데 도움이 되는 'add_data'라는 메서드가 정의되어 있습니다.
- 순환 연결 목록의 노드를 표시하는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
- 'double_list' 클래스의 객체가 생성되고 이중 연결 리스트에 데이터를 추가하기 위해 메소드가 호출됩니다.
- 'add_data_in_middle'은 연결 리스트의 중간 인덱스에 데이터를 추가하기 위해 호출됩니다.
- 이중 연결 리스트의 루트, 헤드, 테일 노드를 None으로 하는 'init' 메소드가 정의되어 있습니다.
- 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.