Khi cần xóa node ở giữa danh sách liên kết vòng, tạo lớp 'Node' với hai thuộc tính: dữ liệu node và tham chiếu node tiếp theo.
Trong danh sách liên kết vòng, head và tail liền kề, kết nối thành vòng tròn, không có 'NULL' ở node cuối.
Tạo lớp có hàm khởi tạo, head khởi tạo là 'None', biến size khởi tạo 0.
Định nghĩa hàm thêm node, in danh sách, xóa node giữa.
Minh họa:
Ví dụ
class Node:
def __init__(self, data):
self.data = data
self.next = None
class list_creation:
def __init__(self):
self.head = Node(None)
self.tail = Node(None)
self.head.next = self.tail
self.tail.next = self.head
self.size = 0
def add_data(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
self.size = int(self.size) + 1
def delete_from_mid(self):
if self.head is None:
return
else:
count = (self.size // 2) if (self.size % 2 == 0) else ((self.size + 1) // 2)
if self.head != self.tail:
temp = self.head
curr = None
for i in range(0, count - 1):
curr = temp
temp = temp.next
if curr is not None:
curr.next = temp.next
temp = None
else:
self.head = self.tail = temp.next
self.tail.next = self.head
temp = None
else:
self.head = self.tail = None
self.size = self.size - 1
def print_it(self):
curr = self.head
if self.head is None:
print("Danh sách rỗng")
return
else:
print(curr.data)
while curr.next != self.head:
curr = curr.next
print(curr.data)
print("\n")
class circular_linked_list:
my_cl = list_creation()
my_cl.add_data(11)
my_cl.add_data(52)
my_cl.add_data(36)
my_cl.add_data(74)
print("Danh sách gốc:")
my_cl.print_it()
while my_cl.head is not None:
my_cl.delete_from_mid()
print("Danh sách sau cập nhật:")
my_cl.print_it()
Đầu ra
Danh sách gốc: 11 52 36 74 Danh sách sau cập nhật: 11 36 74 Danh sách sau cập nhật: 11 74 Danh sách sau cập nhật: 74 Danh sách sau cập nhật: Danh sách rỗng
Giải thích
- Tạo lớp 'Node'.
- Tạo lớp khác với các thuộc tính cần thiết.
- Định nghĩa phương thức 'add_data' thêm dữ liệu vào danh sách.
- Định nghĩa phương thức 'delete_from_mid' xóa phần tử từng cái từ giữa bằng cách xóa tham chiếu.
- Định nghĩa phương thức 'print_it' hiển thị dữ liệu danh sách.
- Tạo đối tượng lớp 'list_creation', gọi phương thức thêm dữ liệu.
- Gọi 'delete_from_mid'.
- Duyệt node, tìm chỉ số giữa và xóa phần tử.
- Hiển thị bằng 'print_it'.