题目描述
判断给定的链表中是否有环。如果有环则返回true,否则返回false。要求空间复杂度为O(1)。
其中,结点的定义如下:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
基本思路
将每次遍历过的结点的next域设置为一个无效值。当访问到一个next域是无效值的结点时,就认为此链表有环。时间复杂度为O(n),空间复杂度为O(1)。
代码实现
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return bool布尔型
#
INVALIDAD = -1
class Solution:
def hasCycle(self , head )->bool:
# write code here
while head and head != INVALIDAD:
pre = head
head = head.next
pre.next = INVALIDAD
if head == INVALIDAD:
return True
return False
缺点
会破坏链表原有结构,非常不现实。