102. Linked List Cycle

题目

https://www.lintcode.com/problem/linked-list-cycle/description?_from=ladder&&fromId=2

实现

  1. 设置快慢指针
  2. 如果快指针追上了慢指针就说明有环

代码

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):
        if head is None or head.next is None:
            return False

        slow = head
        fast = head.next

        while fast is not None and fast.next is not None:
            if slow == fast:
                return True
            slow = slow.next
            fast = fast.next.next

        return False

你可能感兴趣的:(102. Linked List Cycle)