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

Chương trình Python xóa node cuối Danh sách liên kết vòng

Khi cần xóa node ở 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 'linked_list' có hàm khởi tạo, head khởi tạo là 'None'.

Minh họa:

Ví dụ

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

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

    def add_value(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 delete_from_end(self):
        if self.head is None:
            return
        else:
            if self.head != self.tail:
                curr = self.head
                while curr.next != self.tail:
                    curr = curr.next
                self.tail = curr
                self.tail.next = self.head
            else:
                self.head = self.tail = None

    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_list:
    my_cl = linked_list()
    my_cl.add_value(11)
    my_cl.add_value(32)
    my_cl.add_value(43)
    my_cl.add_value(57)
    print("Danh sách gốc:")
    my_cl.print_it()
    while my_cl.head is not None:
        my_cl.delete_from_end()
        print("Danh sách sau khi xóa:")
        my_cl.print_it()

Đầu ra

Danh sách gốc:
11
32
43
57
Danh sách sau khi xóa:
11
32
43
Danh sách sau khi xóa:
11
32
Danh sách sau khi xóa:
11
Danh sách sau khi xóa:
Danh sách rỗng

Giải thích

  • Tạo lớp 'Node'.
  • Tạo lớp 'linked_list' với các thuộc tính cần thiết.
  • Định nghĩa phương thức 'add_value' thêm dữ liệu vào danh sách.
  • Định nghĩa phương thức 'delete_from_end' xóa phần tử từ cuối bằng cách xóa tham chiếu.
  • Định nghĩa phương thức 'print_it' hiển thị dữ liệu danh sách.
  • Tạo đối tượng lớp 'linked_list', gọi phương thức thêm dữ liệu.
  • Hiển thị bằng 'print_it'.