Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Example

Given -21->10->4->5, tail connects to node index 1, return true

Solution

小技巧:

fast 起始位置是head.next 而不是head 否则就一开始就相等了,如果是循环链表,快指针走两步,满指针走一步,快指针早晚会追上满指针的。

while fast and fast.next:

if fast == slow:

return True

"""
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 the linked list.
    @return: True if it has a cycle, or false
    """
    def hasCycle(self, head):
        # write your code here
        if head == None or head.next == None:
            return False
        slow, fast = head, head.next
        while fast and fast.next:
            if fast == slow:
                return True
            slow = slow.next
            fast = fast.next.next
        return False

Last updated

Was this helpful?