Can we do Mark-and-Sweep in this question?


  • 0
    T

    Like that in GC, i mark the val to Integer.MAX_VALUE. This value will be detected if there is a circle exist.


  • 0
    T
    public class Solution {
        public boolean hasCycle(ListNode head) {
            while(head != null)
            {
                if(head.val == Integer.MAX_VALUE)
                    return true;
                head.val = Integer.MAX_VALUE;
                head = head.next;
            }
            return false;
        }
    }
    

  • 0
    C

    @tybk this could work except in the case Integer.MAX_VALUE already exists as the value in any node and this could fail as it is detected even though there may be no cycle. So its not fool proof.


Log in to reply
 

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