Can someone help me to find out the mistakes in my answer? It works on my ide.


  • 0
    public boolean hasCycle(Link head) {
            if(head==null||head.next==null){
                return false;
            }
            Link tmp = head;
            head = head.next;
            tmp.next =null;
            while(head.next!=null){
                head = head.next;
            }
            if(head==tmp){
                return true;
            }
            return false;
        }
    

    The next part is my main function

    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Link link1 = new Link(1);
    		Link link2 = new Link(2);
    		Link link3 = new Link(3);
    		LinkedList linkedList = new LinkedList();
    		linkedList.head = link1;
    		link1.next = link2;
    		link2.next = link3;
    		link3.next = link1;
    		System.out.println(linkedList.hasCycle(linkedList.head));
    	}
    

  • 0

    Thank u guys so so so so so so so so so so so so so so much!


  • 0

    @wxl163530 Your idea is wrong. Here we normally try to utilise two pointers (one slow pointer and one fast pointer) to move forward till:

    • the fast ends the list, which means there is no circle;
    • or the slow meets the fast which means there is a circle.

    Lots of posts are using this, check them if you need.


  • 0

    @LHearen said in Can someone help me to find out the mistakes in my answer? It works on my ide.:

    is, ch
    Yep your suggestion is instructive, I should consider this problem in a common way. Thanks~


Log in to reply
 

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