用于检测链接列表中的循环的 Python 程序

pythonserver side programmingprogramming

当需要检测链接列表中的循环时,会定义一个将元素添加到链接列表的方法和一个获取链接列表中元素的方法。还定义了另一个方法,用于检查头部和尾部值是否相同。根据此结果,可检测到循环。

下面是同样的演示 −

示例

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’ 的方法,用于将值添加到堆栈中。

  • 定义了另一个名为 ‘get_node_val’ 的方法,用于获取链接列表中当前节点的值。

  • 另一个名为 ‘check_cycle’ 的方法已定义,这有助于确定头部和尾部是否相同,这意味着这将是一个循环。

  • 它根据循环的存在与否返回 True 或 False。

  • 创建 ‘LinkedList_structure’ 的实例。

  • 将元素添加到链接列表中。

  • 在此链接列表上调用 ‘check_cycle’ 方法。

  • 输出显示在控制台上。


相关文章