Khi cần tạo danh sách liên kết vòng và hiển thị 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ó '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
class linked_list:
def __init__(self):
self.head = None
def add_data(self, my_data):
new_node = Node(my_data)
new_node.next = self.head
self.head = new_node
def print_it(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
my_list = linked_list()
my_list.add_data(47)
my_list.add_data(89)
my_list.add_data(34)
my_list.add_data(11)
print("Danh sách liên kết vòng là: ")
my_list.print_it()
Đầu ra
Danh sách liên kết vòng là: 11 34 89 47
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'.