题解 | #判断链表中是否有环#

判断链表中是否有环

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
    


全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-29 12:10
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务