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

  • 0

    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||{return false;}
            ListNode p=head;
                p = head;
                if({return true;}
                else{head =; = 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.