เมื่อต้องการแทรกโหนดใหม่ที่ท้ายของ Circular Linked List ต้องสร้างคลาส 'Node' ที่มีแอตทริบิวต์สองอย่าง: ข้อมูลในโหนด และการเข้าถึงโหนดถัดไป
ใน Circular Linked List หัวและท้ายอยู่ติดกัน เชื่อมเป็นวงกลม ไม่มีค่า 'NULL' ในโหนดสุดท้าย
สร้างอีกคลาสหนึ่งมีฟังก์ชันเริ่มต้น และหัวโหนดเริ่มต้นเป็น 'None'
กำหนดเมธอดโดยผู้ใช้สำหรับเพิ่มโหนดท้ายลิสต์ และพิมพ์ค่าโหนด
ตัวอย่าง
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("The list is empty")
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("Nodes are being added to end of list")
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()
ผลลัพธ์
Nodes are being added to end of list 21 21 53 21 53 76
คำอธิบาย
- สร้างคลาส 'Node'
- สร้างคลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็น
- กำหนดเมธอด 'add_at_end' สำหรับเพิ่มข้อมูลท้าย Circular Linked List หลังโหนด 'tail'
- กำหนดเมธอด 'print_it' สำหรับแสดงโหนด
- สร้างออบเจ็กต์ของคลาส 'list_creation' และเรียกใช้เมธอด
- เมธอด 'init' กำหนดโหนดแรกและสุดท้ายเป็น None
- เรียกใช้เมธอด 'add_at_end'
- เมธอดจะหาท้ายลิสต์ เพิ่มองค์ประกอบหลังจากนั้น และอ้างอิงที่อยู่ไปยัง head pointer และ previous pointer
- แสดงผลด้วยเมธอด 'print_it'