순환 연결 리스트의 끝에서 노드를 삭제해야 하는 경우 'Node' 클래스를 생성해야 합니다. 이 클래스에는 노드에 있는 데이터와 연결 목록의 다음 노드에 대한 액세스라는 두 가지 속성이 있습니다.
원형 연결 리스트에서 머리와 뒤쪽은 서로 인접해 있습니다. 연결되어 원을 이루며 마지막 노드에 'NULL' 값이 없습니다.
초기화 기능이 있는 또 다른 'linked_list' 클래스를 생성해야 하며, 노드의 헤드는 'None'으로 초기화됩니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self,data):
self.data = data;
self.next = None;
class linked_list:
def __init__(self):
self.head = Node(None);
self.tail = Node(None);
self.head.next = self.tail;
self.tail.next = self.head;
def add_value(self,my_data):
new_node = Node(my_data);
if self.head.data is None:
self.head = new_node;
self.tail = new_node;
new_node.next = self.head;
else:
self.tail.next = new_node;
self.tail = new_node;
self.tail.next = self.head;
def delete_from_end(self):
if(self.head == None):
return;
else:
if(self.head != self.tail ):
curr = self.head;
while(curr.next != self.tail):
curr = curr.next;
self.tail = curr;
self.tail.next = self.head;
else:
self.head = self.tail = None;
def print_it(self):
curr = self.head;
if self.head is None:
print("The list is empty");
return;
else:
print(curr.data),
while(curr.next != self.head):
curr = curr.next;
print(curr.data),
print("\n");
class circular_list:
my_cl = linked_list();
my_cl.add_value(11);
my_cl.add_value(32);
my_cl.add_value(43);
my_cl.add_value(57);
print("The original list is :");
my_cl.print_it();
while(my_cl.head != None):
my_cl.delete_from_end();
print("The list after deletion is :");
my_cl.print_it(); 출력
The original list is : 11 32 43 57 The list after deletion is : 11 32 43 The list after deletion is : 11 32 The list after deletion is : 11 The list after deletion is : The list is empty
설명
- '노드' 클래스가 생성됩니다.
- 필수 속성이 있는 또 다른 'linked_list' 클래스가 생성됩니다.
- 순환 연결 목록에 데이터를 추가하는 데 사용되는 'add_data'라는 또 다른 메서드가 정의되어 있습니다.
- 참조를 제거하여 끝에서 하나씩 요소를 삭제하는 'delete_from_end'라는 또 다른 메서드가 정의되어 있습니다.
- 연결 목록 데이터를 콘솔에 표시하는 데 사용되는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
- 'linked_list' 클래스의 객체가 생성되고 이에 대한 메소드가 호출되어 데이터를 추가합니다.
- 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.