Finding loop in a singly linked-list

前端 未结 13 1792
梦谈多话
梦谈多话 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 19:17

    Following code will find whether there is a loop in SLL and if there, will return then starting node.

    int find_loop(Node *head){
    
        Node * slow = head;
        Node * fast =  head;
        Node * ptr1;
        Node * ptr2;
        int k =1, loop_found =0, i;
    
        if(!head) return -1;
    
        while(slow && fast && fast->next){
                slow = slow->next;
            /*Moving fast pointer two steps at a time */
                fast = fast->next->next;
                if(slow == fast){
                        loop_found = 1;
                        break;
                }
    
        }
    
        if(loop_found){
        /* We have detected a loop */
        /*Let's count the number of nodes in this loop node */
    
                ptr1  = fast;
                while(ptr1 && ptr1->next != slow){
                        ptr1 = ptr1->next;
                        k++;
                }
        /* Now move the other pointer by K nodes */
                ptr2 = head;
    
                ptr1  = head;
                for(i=0; inext;
                }
    
        /* Now if we move ptr1 and ptr2 with same speed they will meet at start of loop */
    
                while(ptr1 != ptr2){
                        ptr1  = ptr1->next;
                        ptr2 =  ptr2->next;
                }
    
        return ptr1->data;
    
    }
    

提交回复
热议问题