เมื่อจำเป็นต้องแทรกโหนดใหม่ที่ตรงกลางของรายการเชื่อมโยงแบบวงกลม จะต้องสร้างคลาส 'โหนด' ในคลาสนี้ มีแอตทริบิวต์ 2 รายการ ได้แก่ ข้อมูลที่มีอยู่ในโหนด และการเข้าถึงโหนดถัดไปของรายการที่เชื่อมโยง
ในรายการเชื่อมโยงแบบวงกลม ส่วนหัวและส่วนหลังอยู่ติดกัน พวกมันเชื่อมต่อกันเป็นวงกลม และไม่มีค่า 'NULL' ในโหนดสุดท้าย
ต้องสร้างคลาสอื่นที่จะมีฟังก์ชันเริ่มต้น และส่วนหัวของโหนดจะถูกเตรียมข้อมูลเบื้องต้นเป็น 'ไม่มี'
ผู้ใช้กำหนดวิธีการหลายวิธีเพื่อเพิ่มโหนดระหว่างรายการที่เชื่อมโยง และเพื่อพิมพ์ค่าโหนด
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
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
self.size = 0;
def add_data(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
self.size = self.size+1
def add_in_between(self,my_data):
new_node = Node(my_data);
if(self.head == None):
self.head = new_node;
self.tail = new_node;
new_node.next = self.head;
else:
count = (self.size//2) if (self.size % 2 == 0) else ((self.size+1)//2);
temp = self.head;
for i in range(0,count):
curr = temp;
temp = temp.next;
curr.next = new_node;
new_node.next = temp;
self.size = self.size+1;
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 the list")
my_cl.add_data(21)
my_cl.add_data(54)
my_cl.add_data(78)
my_cl.add_data(99)
print("The list is :")
my_cl.print_it();
my_cl.add_in_between(33);
print("The updated list is :")
my_cl.print_it();
my_cl.add_in_between(56);
print("The updated list is :")
my_cl.print_it();
my_cl.add_in_between(0);
print("The updated list is :")
my_cl.print_it(); ผลลัพธ์
Nodes are being added to the list The list is : 21 54 78 99 The updated list is : 21 54 33 78 99 The updated list is : 21 54 33 56 78 99 The updated list is : 21 54 33 0 56 78 99
คำอธิบาย
- คลาส 'โหนด' ถูกสร้างขึ้น
- สร้างคลาสอื่นที่มีคุณสมบัติที่จำเป็นแล้ว
- มีการกำหนดวิธีการอื่นที่ชื่อว่า 'add_in_between' ซึ่งใช้ในการเพิ่มข้อมูลไปยังรายการที่เชื่อมโยงแบบวงกลมที่อยู่ตรงกลาง นั่นคือ ที่ตำแหน่งตรงกลางมากที่สุด
- มีการกำหนดวิธีการอื่นที่ชื่อว่า 'print_it' ซึ่งแสดงโหนดของรายการที่เชื่อมโยงแบบวงกลม
- วัตถุของคลาส 'list_creation' ถูกสร้างขึ้น และมีการเรียกใช้เมธอดเพื่อเพิ่มข้อมูล
- มีการกำหนดวิธีการ 'init' ซึ่งโหนดแรกและโหนดสุดท้ายของรายการที่เชื่อมโยงแบบวงกลมเป็นไม่มี
- เรียกวิธีการ 'add_in_between'
- มันวนซ้ำในรายการ และรับดัชนีส่วนใหญ่ตรงกลางและแทรกองค์ประกอบในตำแหน่งนี้
- แสดงบนคอนโซลโดยใช้เมธอด 'print_it'