Finding loop in a singly linked-list

前端 未结 13 1801
梦谈多话
梦谈多话 2020-11-28 18:41

How can I detect that whether a singly linked-list has loop or not?? If it has loop then how to find the point of origination of the loop i.e. the node from which the loop

13条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 18:56

                    bool FindLoop(struct node *head)
                    {
                        struct node *current1,*current2;
    
                        current1=head;
                        current2=head;
    
                        while(current1!=NULL && current2!= NULL && current2->next!= NULL)
                        { 
                              current1=current1->next;
                              current2=current2->next->next;
    
                              if(current1==current2)
                              {
                                    return true;
                              }
                        }
    
                        return false;
                    }
    

提交回复
热议问题