Khi cần xóa nút ở đầu danh sách liên kết đôi, ta cập nhật head thành nút tiếp theo (head.next) và đặt head.prev = None.
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(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
def delete_from_beginning(self):
if self.head is None:
return
else:
if self.head != self.tail:
self.head = self.head.next
self.head.previous = None
else:
self.head = self.tail = None
my_instance = double_list()
print("Thêm phần tử vào danh sách liên kết đôi")
my_instance.add_data(10)
my_instance.add_data(24)
my_instance.add_data(54)
my_instance.add_data(77)
my_instance.add_data(92)
my_instance.print_it()
while my_instance.head is not None:
my_instance.delete_from_beginning()
print("Danh sách sau khi xóa nút đầu:")
my_instance.print_it()
Kết quả
Thêm phần tử vào danh sách liên kết đôi Các nút trong danh sách liên kết đôi: 10 24 54 77 92 Danh sách sau khi xóa nút đầu: Các nút trong danh sách liên kết đôi: 24 54 77 92 Danh sách sau khi xóa nút đầu: Các nút trong danh sách liên kết đôi: 54 77 92 Danh sách sau khi xóa nút đầu: Các nút trong danh sách liên kết đôi: 77 92 Danh sách sau khi xóa nút đầu: Các nút trong danh sách liên kết đôi: 92 Danh sách sau khi xóa nút đầu: Danh sách rỗng
Giải thích
- Lớp
Nodevàdouble_listcơ bản. delete_from_beginning: nếu head != tail, head = head.next, head.prev = None; nếu chỉ một nút, head=tail=None.- Lặp xóa đầu cho đến khi rỗng.