Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để chèn một nút mới vào cuối Danh sách được liên kết kép

Khi cần chèn một nút mới vào cuối danh sách được liên kết kép, một lớp ‘Node’ cần được tạo. Trong lớp này, có ba thuộc tính, dữ liệu có trong nút, quyền truy cập vào nút tiếp theo của danh sách được liên kết và quyền truy cập vào nút trước đó của danh sách được liên kết.

Dưới đây là một minh chứng cho điều tương tự -

Ví dụ

Nút
class Node:
   def __init__(self, my_data):
      self.prev = None
      self.data = my_data
      self.next = None
class double_list:
   def __init__(self):
      self.head = None
      self.tail = None
   def add_data_at_end(self, my_data):
      new_node = Node(my_data)
      if(self.head == 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 print_it(self):
      curr = self.head
      if (self.head == None):
         print("The list is empty")
         return
      print("The nodes in the doubly linked list are :")
      while curr != None:
         print(curr.data)
         curr = curr.next
my_instance = double_list()
print("Elements are being added to the end of doubly linked list")
my_instance.add_data_at_end(10)
my_instance.print_it()
my_instance.add_data_at_end(24)
my_instance.print_it()
my_instance.add_data_at_end(54)
my_instance.print_it()
my_instance.add_data_at_end(77)
my_instance.print_it()
my_instance.add_data_at_end(92)
my_instance.print_it()

Đầu ra

Elements are being added to the end of doubly linked list
The nodes in the doubly linked list are :
10
The nodes in the doubly linked list are :
10
24
The nodes in the doubly linked list are :
10
24
54
The nodes in the doubly linked list are :
10
24
54
77
The nodes in the doubly linked list are :
10
24
54
77
92

Giải thích

  • Lớp 'Node' đã được tạo.
  • Một lớp khác với các thuộc tính bắt buộc được tạo.
  • Một phương thức có tên ‘add_data_at_end’ được xác định, được sử dụng để thêm dữ liệu vào cuối danh sách được liên kết kép.
  • Một phương thức khác có tên là 'print_it' được xác định, phương thức này sẽ hiển thị các nút của danh sách liên kết vòng tròn.
  • Một đối tượng của lớp 'double_list' được tạo và các phương thức được gọi trên nó để thêm dữ liệu vào cuối danh sách được liên kết đôi.
  • Một phương thức 'init' được xác định, rằng các nút gốc, đầu và cuối của danh sách được liên kết kép thành Không.
  • Danh sách được lặp lại và phần tử được thêm vào cuối danh sách được liên kết kép.
  • Điều này được hiển thị trên bảng điều khiển bằng phương thức "print_it".