Khi cần tạo chương trình Python sinh danh sách liên kết, 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
class circularLinkedList:
def __init__(self):
self.head = None
def add_data(self, my_data):
ptr_1 = Node(my_data)
temp = self.head
ptr_1.next = self.head
if self.head is not None:
while temp.next != self.head:
temp = temp.next
temp.next = ptr_1
else:
ptr_1.next = ptr_1
self.head = ptr_1
def print_it(self):
temp = self.head
if self.head is not None:
while True:
print("%d" % (temp.data))
temp = temp.next
if temp == self.head:
break
my_list = circularLinkedList()
print("Đang thêm phần tử vào danh sách")
my_list.add_data(56)
my_list.add_data(78)
my_list.add_data(12)
print("Dữ liệu là: ")
my_list.print_it()
Đầu ra
Đang thêm phần tử vào danh sách Dữ liệu là: 12 78 56
Giải thích
- Tạo lớp 'Node'.
- Tạo lớp 'circularLinkedList' với các thuộc tính cần thiết.
- Có hàm 'init' khởi tạo phần tử đầu 'head' là 'None'.
- Đị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'.