Problem: Linked List Cycle

Posted by Marcy on February 18, 2015

Question

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

Follow up: Can you solve it without using extra space?

Solution

TODO

Code

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode s = head;
        ListNode f = head;
        while(f != null && f.next != null) {
            s = s.next;
            f = f.next.next;
            if(s==f) return true;
        }
        
        return false;
    }
}

Performance

TODO