Can I destroy the structure of this linklist? It seems no restriction of that appears in the question


  • 0
    S

    Link all nodes' next to head, thus if there is a circle, the pointer will walk to head again.

        bool hasCycle(ListNode *head)
    {
        if(!head) return false;
        ListNode* p = head->next;
        while(p)
        {
            if(p == head) return true;
            ListNode* q = p->next;
            p->next = head;
            p = q;
        }
        return false;
    }

Log in to reply
 

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