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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章