Khi cần chèn node mới vào giữa danh sách liên kết vòng, cần 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ó giá trị 'NULL' ở node cuối.
Cần tạo lớp có hàm khởi tạo, head khởi tạo là 'None'.
Định nghĩa các phương thức thêm node vào giữa và in giá trị node.
Minh họa như sau:
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 = self.size + 1
def add_in_between(self, my_data):
new_node = Node(my_data)
if self.head is None:
self.head = new_node
self.tail = new_node
new_node.next = self.head
else:
count = (self.size // 2) if (self.size % 2 == 0) else ((self.size + 1) // 2)
temp = self.head
for i in range(0, count):
curr = temp
temp = temp.next
curr.next = new_node
new_node.next = temp
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()
print("Đang thêm node vào danh sách")
my_cl.add_data(21)
my_cl.add_data(54)
my_cl.add_data(78)
my_cl.add_data(99)
print("Danh sách là:")
my_cl.print_it()
my_cl.add_in_between(33)
print("Danh sách sau cập nhật:")
my_cl.print_it()
my_cl.add_in_between(56)
print("Danh sách sau cập nhật:")
my_cl.print_it()
my_cl.add_in_between(0)
print("Danh sách sau cập nhật:")
my_cl.print_it()
Đầu ra
Đang thêm node vào danh sách Danh sách là: 21 54 78 99 Danh sách sau cập nhật: 21 54 33 78 99 Danh sách sau cập nhật: 21 54 33 56 78 99 Danh sách sau cập nhật: 21 54 33 0 56 78 99
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_in_between' để thêm dữ liệu vào vị trí giữa của danh sách liên kết vòng.
- Định nghĩa phương thức 'print_it' để hiển thị các node.
- Tạo đối tượng lớp 'list_creation', gọi phương thức thêm dữ liệu.
- Phương thức 'init' khởi tạo node đầu và cuối là None.
- Gọi phương thức 'add_in_between'.
- Phương thức duyệt danh sách, tìm chỉ số giữa và chèn phần tử tại vị trí đó.
- Hiển thị kết quả bằng 'print_it'.