이중 연결 목록의 시작 부분에서 노드를 삭제해야 하는 경우 '노드' 클래스를 생성해야 합니다. 이 클래스에는 노드에 있는 데이터, 연결 목록의 다음 노드에 대한 액세스, 연결 목록의 이전 노드에 대한 액세스의 세 가지 속성이 있습니다.
아래는 동일한 데모입니다 -
예시
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(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 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 delete_from_beginning(self):
if(self.head == None):
return;
else:
if(self.head != self.tail):
self.head = self.head.next;
self.head.previous = None;
else:
self.head = self.tail = None;
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)
my_instance.add_data(77)
my_instance.add_data(92)
my_instance.print_it()
while(my_instance.head != None):
my_instance.delete_from_beginning();
print("The list after deleting the element from the beginning is : ");
my_instance.print_it(); 출력
Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 24 54 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 54 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 92 The list after deleting the element from the beginning is : The list is empty
설명
- '노드' 클래스가 생성됩니다.
- 필수 속성이 있는 다른 클래스가 생성됩니다.
- 이중 연결 목록에 데이터를 추가하는 데 사용되는 'add_data'라는 메서드가 정의되어 있습니다.
- 순환 연결 목록의 노드를 표시하는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
- 'delete_from_beginning'이라는 또 다른 메서드가 정의되어 있습니다. 이 메서드는 시작부터 노드, 즉 'head' 노드를 삭제하고 다음 노드를 순환 연결 목록의 헤드 노드로 만듭니다.
- 'double_list' 클래스의 객체가 생성되고, 이중 연결 리스트의 시작 부분에서 노드를 삭제하기 위해 메소드가 호출됩니다.
- 이중 연결 리스트의 루트, 헤드, 테일 노드를 None으로 하는 'init' 메소드가 정의되어 있습니다.
- 목록은 반복되며 처음부터 모든 노드는 비어 있을 때까지 삭제됩니다.
- 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.