I am a fresher in LEETCODE. Who can tell why it can not work.


  • 0
    L
            class Solution {
    public:
        bool hasCycle(ListNode *head) {
        ListNode *n,*h;
        if(head==NULL)
            return false;
        if(head->next==NULL)
            return false;
        if(head->next==head)
            return true;
        h=head;
        n=head->next;
        while(n->next!=NULL)
        {
            if(n->next==n)
            {
                return true;
                break;
            }
            if(n->next==head)
            {
                return true;
                break;
            }
            else
            {  
                head=head->next;
                if(head==n)
                {
                    n=n->next;
                    head=h;
                }
            }
        }
        return false;
        }
    };

  • 0
    S

    dont try to make it complex first take an example trace it on paper,and write some psuedo code see how that works,then try for optimisation .


Log in to reply
 

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