题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
将每次遍历过的结点的next域设置为一个无效值。当访问到一个next域是无效值的结点时,就认为此链表有环。
# 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