Linked List Cycle

Problem: Linked List Cycle

We can use two pointers, one running fast and one running slow. If they meet with each other again, it means there's a cycle. If not, the fast pointer will get to the tail of list.

Code in Python:

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        i, j = head, head
        while j and j.next:
            i, j = i.next, j.next.next
            if i == j and i != None: return True
        return False

results matching ""

    No results matching ""