Why this code has run time error: last execute {}, no cycle?


  • 0
    S
    class ListNode {
          int val;
          ListNode next;
          ListNode(int x) {
              val = x;
              next = null;
          }
     }
     
    public class Solution {
        public boolean hasCycle(ListNode head) {
            ListNode curr = null;
            ListNode prev = null;
            
            curr = head;
             //faster = head.next; //start faster one node ahead
                while(true) {
                    // if the faster pointer encounters a NULL element
                     if(curr == null || curr.next == null)
                        return false;
                    //if faster pointer ever equals slower or faster's next
                    //pointer is ever equal to slow then it's a circular list
                    else if (curr == prev || curr.next == prev)
                        return true;
                    else{
                        // advance the pointers
                        prev = curr;
                        curr = curr.next;
                    }
                 }
        }
    }

  • 0
    S

    Pay attention to "Writing code? Select all code then click on the button to preserve code formatting.” above text editor.


  • 0
    B

    I have seen a "last exectue" message in one of my submissions. For me it turned out that the last executed testcase was not the one with runtime error. Given that it prints "no cycle" as output for your "last execute", I am guessing your runtime error is with some other testcase.


  • 0
    K

    comment this part of your code.

    class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
    

    }

    By the way you are trying to solve it using Floyd's cycle detection method. But your logic is need to be modified else you will get time limit exceed error.


Log in to reply
 

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