09 Aug 2020

GeeksForGeeks - Detect Loop in Linked List

  • algorithm
  • must_do
  • LinkedList
  • geeks
  • link

    Problem

    Given a linked list of N nodes. The task is to check if the the linked list has a loop. Linked list can contain self loop.

    Solution

    struct Node
    {
        int data;
        struct Node *next;
        Node(int x) {
            data = x;
            next = NULL;
        }
    
    
    bool detectLoop(Node* head)
    {
        // your code here
        while(head){
            if(head->data < 0){
                return true;
            }
            head->data *= -1;
            head = head->next;
        }
        return false;
    }
    
    

    Time Complexity : O(n)