检测链表中循环的 Python 程序
当需要检测链表中的循环时,定义了向链表添加元素的方法和获取链表中元素的方法。定义了另一种方法来检查头部和尾部值是否相同。基于该结果,检测循环。
以下是相同的演示-
示例
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): ifself.last_nodeis 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'函数,用于初始化第一个元素,i.e即'head'为'None'。
定义了一个名为“add_vals”的方法,它有助于向堆栈添加一个值。
定义了另一个名为“get_node_val”的方法,它有助于获取链表中当前节点的值。
定义了另一个名为“check_cycle”的方法,它有助于确定头部和尾部是否相同,这意味着这将是一个循环。
它根据循环的存在与否返回True或False。
'LinkedList_structure'的一个实例被创建。
元素被添加到链表中。
'check_cycle'方法在这个链表上被调用。
输出显示在控制台上。