การค้นหาข้อมูลใน Circular Linked List ด้วย Python
เมื่อต้องการค้นหาเอลีเมนต์ใน Circular Linked List เราต้องสร้างคลาส Node ก่อน ซึ่งมีแอตทริบิวต์สองอย่าง ได้แก่ ข้อมูลที่เก็บในโหนด (data) และการอ้างอิงไปยังโหนดถัดไป (next)
ลักษณะของ Circular Linked List
ใน Circular Linked List หัว (head) และท้าย (tail) จะอยู่ติดกันและเชื่อมต่อกันเป็นวงกลม โหนดสุดท้ายจะไม่มีค่า NULL แต่จะชี้กลับไปที่หัวแทน
เราจะสร้างคลาสอีกหนึ่งคลาสที่มีฟังก์ชัน initialization และกำหนดให้ head เริ่มต้นเป็น None พร้อมกับกำหนดเมธอดต่างๆ สำหรับเพิ่มโหนด ค้นหาโหนด และแสดงข้อมูลโหนด
ตัวอย่างโค้ด
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
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 is None:
print("The list is empty")
else:
while True:
if curr.data == elem_to_search:
flag_val = True
break
curr = curr.next
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")
# การใช้งาน
cl = CircularLinkedList()
print("Nodes are being added to the list")
cl.add_data(21)
cl.add_data(54)
cl.add_data(78)
cl.add_data(99)
cl.add_data(27)
print("The list is :")
cl.print_it()
print("Value 99 is being searched")
cl.search_value(99)
print("Value 0 is being searched")
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
คำอธิบาย
- สร้างคลาส
Nodeเพื่อเก็บข้อมูลและลิงก์ไปยังโหนดถัดไป - สร้างคลาส
CircularLinkedListพร้อมเมธอด initialization และจัดการโหนด - เมธอด
search_valueใช้สำหรับค้นหาเอลีเมนต์ในลิงก์ลิสต์ - เมธอด
print_itใช้แสดงข้อมูลของโหนดทั้งหมด - สร้างอ็อบเจกต์ของคลาส
CircularLinkedListและเรียกใช้เมธอดต่างๆ - เมธอด
search_valueจะวนลูปผ่านลิสต์เพื่อตรวจสอบว่าเอลีเมนต์ที่ต้องการมีอยู่หรือไม่ - หากพบ จะแสดงตำแหน่ง (index) ของเอลีเมนต์นั้น
- ผลลัพธ์จะแสดงผ่านเมธอด
print_it