Finding loop in a singly linked-list

前端 未结 13 1696
梦谈多话
梦谈多话 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:20

    Firstly, Create a Node

    struct Node { 
        int data; 
        struct Node* next; 
    }; 
    

    Initialize head pointer globally

    Struct Node* head = NULL;
    

    Insert some data in Linked List

    void insert(int newdata){
    
        Node* newNode = new Node();
        newNode->data = newdata;
        newNode->next = head;
        head = newNode;
    }
    

    Create a function detectLoop()

    void detectLoop(){
        if (head == NULL || head->next == NULL){
            cout<< "\nNo Lopp Found in Linked List";
        }
        else{
            Node* slow = head;
            Node* fast = head->next;
            while((fast && fast->next) && fast != NULL){
                if(fast == slow){
                    cout<<"Loop Found";
                    break;
                }
                fast = fast->next->next;
                slow = slow->next;
            }
            if(fast->next == NULL){
                cout<<"Not Found";
            }
        }
    }
    

    Call the function from main()

    int main() 
    { 
        insert(4);
        insert(3);
        insert(2);
        insert(1);
    
        //Created a Loop for Testing, Comment the next line to check the unloop linkedlist
        head->next->next->next->next = head->next;
    
        detectLoop();
        //If you uncomment the display function and make a loop in linked list and then run the code you will find infinite loop 
        //display();
    } 
    
    0 讨论(0)
提交回复
热议问题