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):
      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”方法。

  • 在控制台上显示输出。

更新于: 2021年4月14日

374 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告

© . All rights reserved.