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 đầu Danh sách liên kết vòng

Khi cần chèn node mới vào đầu 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 ở đầu 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_beginning(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:
            temp = self.head
            new_node.next = temp
            self.head = 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 giá trị vào danh sách")
    my_cl.add_at_beginning(21)
    my_cl.print_it()
    my_cl.add_at_beginning(53)
    my_cl.print_it()
    my_cl.add_at_beginning(76)
    my_cl.print_it()

Đầu ra

Đang thêm giá trị vào danh sách
21
53
21
76
53
21

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