给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
解释:每遍历一个结点就给它赋值(由于题目都是数字,因此赋值字符串),当后面结点的下一个结点的值为标记的字符串说明该结点为之前的结点,即之前进行过遍历,即有环.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head:
if head.val == 'trami':
return True
head.val = 'trami'
head = head.next
return False