102. 带环链表
给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
挑战
不要使用额外的空间
实现代码:
思路:
快慢指针的典型应用,使用快指针 fast 与慢指针 slow,slow每次后移一位,fast 每次后移两位,当fast 与 slow 指向同一节点时,说明存在环。就如同操场跑圈时,领先一圈的人会遇上跑在他后面的人那样。
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The first node of linked list.
@return: True if it has a cycle, or false
"""
def hasCycle(self, head):
# write your code here
if head is None or head.next is None:
return False
slow, fast = head, head.next
while fast and fast.next:
if slow == fast:return True
slow, fast = slow.next, fast.next.next
return False