给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
思路:使用两个指针,一个每走一步,另一个每走两步。
若无环,则两步指针优先走完返回None值,
若有环,则两指针都会进入环内,并值相等。
# 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
"""
if not head:
return False
cur1 = cur2 = head
while cur2 and cur2.next:
cur1 = cur1.next
cur2 = cur2.next.next
if cur1 == cur2:
return True
return False