Python 检测链表中的循环
当链表中的任何节点不指向NULL时,链表被称为具有循环。最后一个节点将指向链表中的其中一个先前节点,从而创建一个循环。具有循环的链表将没有结束。
在下面的示例中,最后一个节点(节点5)不指向NULL。而是指向节点3,并且建立了一个循环。因此,上述链表没有结束。
算法采用双指针快指针和慢指针
- 两个指针最初都指向链表的头部。
-
慢指针每次移动一个节点,快指针每次移动两个节点。
-
在任何时刻,如果快指针和慢指针指向同一个节点,则说明链表存在环。
考虑以下示例,其中最后一个节点指向第二个节点 –
示例
慢指针和快指针都指向同一个节点。因此,可以得出结论,给定的链表包含一个环。
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_the_end(self,newVal):
newNode=Node(newVal)
if self.head==None:
self.head=newNode
return
temp=self.head
while(temp.next):
temp=temp.next
temp.next=newNode
def Print_the_LL(self):
temp = self.head
if(temp != None):
print("\nThe linked list elements are:", end=" ")
while (temp != None):
print(temp.val, end=" ")
temp = temp.next
else:
print("The list is empty.")
def detect_loop(self):
slow=self.head
fast=self.head
while(fast):
if slow==fast:
print("\nA loop has been detected in the linked list ")
return
slow=slow.next
fast=fast.next
newList = LinkedList()
newList.insert_at_the_end(1)
newList.insert_at_the_end(2)
newList.insert_at_the_end(3)
newList.insert_at_the_end(4)
newList.Print_the_LL()
print("\n")
newList.head.next.next.next.next=newList.head.next
newList.detect_loop()
输出
检测到链表中存在循环。
The linked list elements are: 1 2 3 4
A loop has been detected in the linked list