Khi cần chèn nút mới vào cuối danh sách liên kết đôi, ta dùng lớp Node và lớp quản lý với head, tail. Phương thức thêm vào cuối cập nhật tail.
Ví dụ
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
class double_list:
def __init__(self):
self.head = None
self.tail = None
def add_data_at_end(self, my_data):
new_node = Node(my_data)
if self.head is None:
self.head = self.tail = new_node
self.head.previous = None
self.tail.next = None
else:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
self.tail.next = None
def print_it(self):
curr = self.head
if self.head is None:
print("Danh sách rỗng")
return
print("Các nút trong danh sách liên kết đôi:")
while curr is not None:
print(curr.data)
curr = curr.next
my_instance = double_list()
print("Thêm phần tử vào cuối danh sách liên kết đôi")
my_instance.add_data_at_end(10)
my_instance.print_it()
my_instance.add_data_at_end(24)
my_instance.print_it()
my_instance.add_data_at_end(54)
my_instance.print_it()
my_instance.add_data_at_end(77)
my_instance.print_it()
my_instance.add_data_at_end(92)
my_instance.print_it()
Kết quả
Thêm phần tử vào cuối danh sách liên kết đôi Các nút trong danh sách liên kết đôi: 10 Các nút trong danh sách liên kết đôi: 10 24 Các nút trong danh sách liên kết đôi: 10 24 54 Các nút trong danh sách liên kết đôi: 10 24 54 77 Các nút trong danh sách liên kết đôi: 10 24 54 77 92
Giải thích
- Lớp
Nodevới prev, data, next. - Lớp
double_listquản lý head, tail. add_data_at_end: nếu rỗng, head=tail=new_node; ngược lại nối new_node sau tail, cập nhật tail.print_itduyệt từ head in dữ liệu.- Demo thêm lần lượt 10,24,54,77,92 và in sau mỗi lần.