Linked List Cycle

Question

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

Tags

  • Linked List
  • Two Pointers

Thoughts

Use the two pointers method: fast pointer and the slow pointer.

Code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        # use the two fast-slow pointer methods
        fast = head
        slow = head
        while fast is not None and fast.next is not None:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return True
        return False

results matching ""

    No results matching ""