Easy two pointer solution. O(1) space complexity. Java


  • 2
    O
    public class Solution {
        public boolean hasCycle(ListNode head) {
        	if (head == null) {
        		return false;
        	}
            ListNode slow = head, fast = head;
            do {
                if (fast.next != null && fast.next.next != null) {
                    slow = slow.next;
                    fast = fast.next.next;
                } else {
                    return false;
                }
                if (slow == fast) {
                    return true;
                }
            } while(true);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.