เมื่อจำเป็นต้องค้นหาองค์ประกอบในรายการเชื่อมโยงแบบวงกลม จะต้องสร้างคลาส 'โหนด' ในคลาสนี้ มีแอตทริบิวต์ 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
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
def search_value(self,elem_to_search):
curr = self.head;
i = 1;
flag_val = False;
if(self.head == None):
print("The list is empty");
else:
while(True):
if(curr.data == elem_to_search):
flag_val = True;
break;
curr = curr.next;
i = i + 1;
if(curr == self.head):
break;
if(flag_val):
print("The element is present in list at position : " + str(i));
else:
print("The element is not present in list");
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)
my_cl.add_data(27)
print("The list is :")
my_cl.print_it()
print("Value 99 is being searched")
my_cl.search_value(99)
print("Value 0 is being searched")
my_cl.search_value(0) ผลลัพธ์
Nodes are being added to the list The list is : 21 54 78 99 27 Value 99 is being searched The element is present in list at position : 4 Value 0 is being searched The element is not present in list
คำอธิบาย
- สร้างคลาส 'โหนด' แล้ว
- สร้างคลาสอื่นที่มีคุณสมบัติที่จำเป็นแล้ว
- มีการกำหนดวิธีการอื่นที่เรียกว่า 'search_value' ซึ่งใช้ในการค้นหาองค์ประกอบเฉพาะในรายการที่เชื่อมโยง
- มีการกำหนดวิธีการอื่นที่ชื่อว่า 'print_it' ซึ่งแสดงโหนดของรายการที่เชื่อมโยงแบบวงกลม
- วัตถุของคลาส 'list_creation' จะถูกสร้างขึ้น และมีการเรียกใช้เมธอดเพื่อเพิ่มข้อมูล
- มีการกำหนดวิธีการ 'init' ซึ่งโหนดแรกและโหนดสุดท้ายของรายการที่เชื่อมโยงแบบวงกลมเป็นไม่มี
- มีการเรียกเมธอด 'search_value'
- จะวนซ้ำในรายการ และตรวจสอบว่าพบองค์ประกอบที่จำเป็นต้องค้นหาหรือไม่
- หากพบ ดัชนีจะปรากฏขึ้น
- แสดงบนคอนโซลโดยใช้วิธี "print_it"