Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python tạo và hiển thị danh sách liên kết đôi


Khi cần tạo và hiển thị danh sách liên kết đôi, ta định nghĩa lớp Node (prev, data, next) và lớp quản lý với head, 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(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 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()

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

Giải thích

  • Lớp Node đại diện nút.
  • Lớp double_list quản lý head, tail.
  • add_data thêm vào cuối, cập nhật con trỏ prev/next.
  • print_it duyệt từ head in dữ liệu.
  • Tạo instance, thêm 5 phần tử, in danh sách.