เมื่อจำเป็นต้องตรวจจับวัฏจักรในรายการที่เชื่อมโยง วิธีการเพิ่มองค์ประกอบในรายการที่เชื่อมโยง และวิธีการรับองค์ประกอบในรายการที่เชื่อมโยงจะถูกกำหนด มีการกำหนดวิธีอื่นที่ตรวจสอบว่าค่า head และ rear เท่ากันหรือไม่ จากผลลัพธ์นี้ ตรวจพบวัฏจักร
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList_structure: def __init__(self): self.head = None self.last_node = None def add_vals(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next def get_node_val(self, index): curr = self.head for i in range(index): curr = curr.next if curr is None: return None return curr def check_cycle(my_list): slow_val = my_list.head fast_val = my_list.head while (fast_val != None and fast_val.next != None): slow_val = slow_val.next fast_val = fast_val.next.next if slow_val == fast_val: return True return False my_linked_list = LinkedList_structure() my_list = input('Enter the elements in the linked list ').split() for elem in my_list: my_linked_list.add_vals(int(elem)) my_len = len(my_list) if my_len != 0: vals = '0-' + str(my_len - 1) last_ptr = input('Enter the index [' + vals + '] of the node' ' at which the last node has to point'' (Enter nothing to point to None): ').strip() if last_ptr == '': last_ptr = None else: last_ptr = my_linked_list.get_node_val(int(last_ptr)) my_linked_list.last_node.next = last_ptr if check_cycle(my_linked_list): print("The linked list has a cycle") else: print("The linked list doesn't have a cycle")
ผลลัพธ์
Enter the elements in the linked list 56 78 90 12 4 Enter the index [0-4] of the node at which the last node has to point (Enter nothing to point to None): The linked list doesn't have a cycle
คำอธิบาย
-
สร้างคลาส "โหนด" แล้ว
-
'LinkedList_structure' คลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็นจะถูกสร้างขึ้น
-
มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None'
-
มีการกำหนดเมธอดชื่อ 'add_vals' ซึ่งช่วยเพิ่มมูลค่าให้กับสแต็ก
-
มีการกำหนดวิธีการอื่นที่เรียกว่า 'get_node_val' ซึ่งช่วยให้ได้ค่าของโหนดปัจจุบันในรายการที่เชื่อมโยง
-
มีการกำหนดวิธีการอื่นที่เรียกว่า 'check_cycle' ซึ่งจะช่วยค้นหาว่าส่วนหัวและส่วนหลังเหมือนกันหรือไม่ ซึ่งหมายความว่าจะเป็นวงจร
-
คืนค่า True หรือ False ขึ้นอยู่กับการมีหรือไม่มีวงจร
-
อินสแตนซ์ของ 'LinkedList_structure' ถูกสร้างขึ้น
-
เพิ่มองค์ประกอบในรายการที่เชื่อมโยง
-
วิธี 'check_cycle' ถูกเรียกในรายการที่เชื่อมโยงนี้
-
เอาต์พุตจะแสดงบนคอนโซล