Simple Java O(1) space solution but breaks the structure of linked list.


  • 0
    H

    This is my O(1) space solution for Java. It breaks the structure of the linked list. Kinda troll but works fine.

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head==null||head.next==null){return false;}
            ListNode p=head;
            while(head.next!=null){
                p = head;
                if(head.next==head.next.next){return true;}
                else{head = head.next;p.next = p;} //Let the next pointer of visited node points to the node itself. 
            }
            return false;
        }
    }

Log in to reply
 

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