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

Chương trình Python chèn node mới vào cuối Danh sách liên kết vòng

Khi cần chèn node mới vào cuối 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 ở cuối và in giá trị node.

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_at_end(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 print_it(self):
        curr = self.head
        if self.head is None:
            print("Danh sách rỗng")
            return
        else:
            print(curr.data)
            while curr.next != self.head:
                curr = curr.next
                print(curr.data)
            print("\n")

class circular_linked_list:
    my_cl = list_creation()
    print("Đang thêm node vào cuối danh sách")
    my_cl.add_at_end(21)
    my_cl.print_it()
    my_cl.add_at_end(53)
    my_cl.print_it()
    my_cl.add_at_end(76)
    my_cl.print_it()

Đầu ra

Đang thêm node vào cuối danh sách
21
21
53
21
53
76

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_at_end' để thêm dữ liệu vào cuối danh sách liên kết vòng (sau node 'tail').
  • Định nghĩa phương thức 'print_it' để hiển thị các node.
  • 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 phương thức 'add_at_end'.
  • Phương thức lấy tail của danh sách, thêm phần tử sau nó, tham chiếu địa chỉ tới head và node trước.
  • Hiển thị kết quả bằng 'print_it'.