Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python ตรวจจับวัฏจักร (Cycle) ใน Linked List


ภาพรวม

เมื่อต้องการตรวจจับวัฏจักรใน Linked List จะนิยามเมธอดเพิ่มองค์ประกอบ และเมธอดดึงค่าของโหนด นิยามเมธอดอีกตัวตรวจสอบว่าโหนด 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

คำอธิบาย

  • สร้างคลาส Node
  • สร้างคลาส LinkedList_structure พร้อมแอตทริบิวต์ที่จำเป็น
  • เมธอด __init__ เริ่มต้นโหนดแรก (head) เป็น None
  • เมธอด add_vals เพิ่มค่าเข้า Linked List
  • เมธอด get_node_val ดึงค่าของโหนดปัจจุบันใน Linked List
  • เมธอด check_cycle ตรวจสอบว่า head และ rear เหมือนกันหรือไม่ (หมายถึงมีวัฏจักร)
  • คืนค่า True หรือ False ขึ้นอยู่กับการมีหรือไม่มีวัฏจักร
  • สร้างอินสแตนซ์ของ LinkedList_structure
  • เพิ่มองค์ประกอบเข้า Linked List
  • เรียกเมธอด check_cycle กับ Linked List นี้
  • แสดงผลลัพธ์บนคอนโซล