Need help for Linked List Cycle


  • 0
    K

    Can anyone tell me why I am wrong? I get TLE and "[3,2,0,-4] tail connects to node index 1"

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null) {
                return false;
            }
            ListNode current = head.next;
            while(current != head && current != null) {
                current = current.next;
            }
            if (current == head) {
                return true;
            }
            if (current == null) {
                return false;
            }
            return false;
        }
    }
    

  • 0

    You are checking with head only if there is cycle after head eg you have link list with node 1-10 and there is cycle from node 10 to node 3 so you never came back to head. so how you going to get out from loop.
    try 2 pointer with one with sigle step and one with double step for understanding onece they meet there is cycle other wise you will hit NULL.


  • 0
    K
    This post is deleted!

Log in to reply
 

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