My simple O(n) C++ code


  • -3
    F

    why Time Limit Exceeded?

      class Solution {
        public:
            ListNode *detectCycle(ListNode *head) {
                ListNode *tmp = NULL;
                
                while(head){
                    tmp = head->next;
                    if(head==head->next){
                        return head;
                    } else {
                        head->next = head;
                    }
                    head = tmp;
                }
                
                return NULL;
            }
        };

  • 0
    O

    Your code will lead to infinite loop. The cycle is not between two node but one or more.


  • 0
    C

    agree. and moreover, the nodes become memory blocks without any pointers point to them.


Log in to reply
 

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