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

判断链表中是否有环

http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param head ListNode类 
# @return bool布尔型
#
class Solution:
    def hasCycle(self , head: ListNode) -> bool:
        if head == None:
            return False
        head.val = 999999
        temp = None
        p = head
        while p:
            temp = p.next
            if temp and temp.val == 999999: 
            # 遍历完一个节点以后给他设置为一个不可能的数,若以后遍历到了,则有环
                return True
            p.val = 999999
            p = temp
        return False
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务