Khi cần tạo danh sách liên kết vòng và hiển thị theo thứ tự ngược, tạo lớp 'Node'. Để hiển thị dữ liệu theo thứ tự ngược, định nghĩa phương thức đảo ngược dữ liệu. 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 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 reverse(self):
prev = None
current = self.head
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
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 là: ")
my_list.print_it()
print("Đang đảo ngược danh sách")
my_list.reverse()
print("Danh sách đã đảo ngược: ")
my_list.print_it()
Đầu ra
Danh sách là: 11 34 89 47 Đang đảo ngược danh sách Danh sách đã đảo ngược: 47 89 34 11
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 'reverse' đảo ngược dữ liệu trong danh sách liên kết vòng.
- Đị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', thêm dữ liệu.
- Đảo ngược bằng phương thức 'reverse'.
- Hiển thị bằng 'print_it'.