Khi cần tạo danh sách liên kết vòng có 'N' node và đếm số node, tạo lớp 'Node'. Để hiển thị dữ liệu, định nghĩa phương thức hiển thị. Lớp 'Node' có 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 'linked_list' có hàm khởi tạo, head khởi tạo là 'None'.
Minh họa:
Ví dụ
class Node:
def __init__(self, my_data):
self.data = my_data
self.next = None
def add_data(head_ref, my_data):
ptr_1 = Node(0)
temp = head_ref
ptr_1.data = my_data
ptr_1.next = head_ref
if head_ref is not None:
while temp.next != head_ref:
temp = temp.next
temp.next = ptr_1
else:
ptr_1.next = ptr_1
head_ref = ptr_1
return head_ref
def count_node(head):
temp = head
result = 0
if head is not None:
while True:
temp = temp.next
result = result + 1
if temp == head:
break
return result
if __name__ == '__main__':
head = None
head = add_data(head, 78)
head = add_data(head, 56)
head = add_data(head, 22)
print("Đã thêm phần tử vào danh sách")
print("Số node là: ")
print(count_node(head))
Đầu ra
Đã thêm phần tử vào danh sách Số node là: 3
Giải thích
- Tạo lớp 'Node'.
- Tạo lớp 'linked_list' 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 'print_it' hiển thị dữ liệu danh sách.
- Tạo đối tượng lớp 'linked_list', gọi phương thức thêm dữ liệu.
- Hiển thị bằng 'print_it'.