Java 1ms AC O(1) space two pointers


  • 4
    P
    public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null) return false;
        ListNode oneStep = head.next;
        ListNode twoStep = head.next.next;
        
        while(oneStep!=twoStep){
            if(oneStep==null||twoStep==null) return false;
            if(twoStep.next==null) return false;
            else{
                oneStep = oneStep.next;
                twoStep = twoStep.next.next;
            }
        }
        return true;
    }

Log in to reply
 

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