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

Chương trình Python tìm node có giá trị lớn nhất và nhỏ nhất trong Danh sách liên kết vòng

Khi cần tìm giá trị lớn nhất và nhỏ nhất của node trong danh sách liên kết vòng, tạo lớp 'Node' với 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 có hàm khởi tạo, head khởi tạo là 'None'.

Định nghĩa phương thức thêm node, tìm min/max và hiển thị.

Minh họa:

Ví dụ

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

class list_creation:
    def __init__(self):
        self.head = Node(None)
        self.tail = Node(None)
        self.head.next = self.tail
        self.tail.next = self.head

    def add_data(self, my_data):
        new_node = Node(my_data)
        if self.head.data is None:
            self.head = new_node
            self.tail = new_node
            new_node.next = self.head
        else:
            self.tail.next = new_node
            self.tail = new_node
            self.tail.next = self.head

    def find_min_node(self):
        curr = self.head
        min_val = self.head.data
        if self.head is None:
            print("Danh sách rỗng")
        else:
            while True:
                if min_val > curr.data:
                    min_val = curr.data
                curr = curr.next
                if curr == self.head:
                    break
            print("Node có giá trị nhỏ nhất: " + str(min_val))

    def find_max_node(self):
        curr = self.head
        max_val = self.head.data
        if self.head is None:
            print("Danh sách rỗng")
        else:
            while True:
                if max_val < curr.data:
                    max_val = curr.data
                curr = curr.next
                if curr == self.head:
                    break
            print("Node có giá trị lớn nhất: " + str(max_val))

class circular_linked_list:
    my_cl = list_creation()
    print("Đã thêm giá trị vào danh sách")
    my_cl.add_data(11)
    my_cl.add_data(52)
    my_cl.add_data(36)
    my_cl.add_data(74)
    my_cl.find_max_node()
    my_cl.find_min_node()

Đầu ra

Đã thêm giá trị vào danh sách
Node có giá trị lớn nhất: 74
Node có giá trị nhỏ nhất: 11

Giải thích

  • Tạo lớp 'Node'.
  • Tạo lớp khác 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 liên kết vòng.
  • Định nghĩa phương thức 'find_max_node' duyệt danh sách tìm giá trị lớn nhất.
  • Định nghĩa phương thức 'find_min_node' duyệt danh sách tìm giá trị nhỏ nhất.
  • Tạo đối tượng lớp 'list_creation', gọi phương thức thêm dữ liệu.
  • Phương thức 'init' khởi tạo node đầu và cuối là None.
  • Gọi 'find_max_node' và 'find_min_node'.
  • Duyệt các node, tìm max/min và hiển thị.