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

Chương trình Python tạo danh sách liên kết đôi n nút và đếm số nút


Khi cần đếm số nút trong danh sách liên kết đôi, ta duyệt từ head đến tail, tăng bộ đếm.

Ví dụ

class Node:
    def __init__(self, my_data):
        self.prev = None
        self.data = my_data
        self.next = None

class count_val:
    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 count_node(self):
        my_counter = 0
        curr = self.head
        while curr is not None:
            my_counter += 1
            curr = curr.next
        return my_counter

    def print_it(self):
        curr = self.head
        if self.head is None:
            print("Danh sách rỗng")
            return
        print("Các nút:")
        while curr is not None:
            print(curr.data)
            curr = curr.next

my_instance = count_val()
print("Thêm phần tử vào danh sách")
my_instance.add_data(10)
my_instance.add_data(14)
my_instance.add_data(24)
my_instance.add_data(17)
my_instance.add_data(22)
my_instance.print_it()
print("Số nút trong danh sách liên kết đôi:")
print(my_instance.count_node())

Kết quả

Thêm phần tử vào danh sách
Các nút:
10
14
24
17
22
Số nút trong danh sách liên kết đôi:
5

Giải thích

  • Lớp Node và count_val.
  • count_node khởi tạo counter=0, duyệt curr từ head, tăng counter cho mỗi nút.
  • Trả về counter.
  • Demo thêm 5 phần tử, in danh sách, in số lượng nút.