**Description**Hints**Submissions**Solutions

Total Accepted: 177986 Total Submissions: 502453 Difficulty: Easy Contributor: LeetCode

Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space?

Hide Company Tags  Amazon Microsoft Bloomberg Yahoo Hide Tags  Linked List Two Pointers Hide Similar Problems  (M) Linked List Cycle II

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    /*
      Use two pointers, slower and faster.
        slower moves step by step. faster moves two steps at time.
        if the Linked List has a cycle slower and faster will meet at some
        point.
    */
    public boolean hasCycle(ListNode head) {
        ListNode slow = new ListNode(0);
        ListNode fast = new ListNode(0);
        slow.next = head;
        fast.next = head;
        
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
             if (fast == slow) {
                return true;
            }
        }
        return false;
    }