Friday, June 18, 2021
Home coding write a program to check loop in linkedlist.

write a program to check loop in linkedlist.

Given a linkedlist ,we have to check the loop present in a linkedlist or not.

Logic:

STEP 1:start traversing a linkedlist ,till it reach its end of linkedlist.
STEP 2:store all the node in map.
STEP 3:if any node is already existed then there is loop,otherwise not.

Code

bool CheckLoop(struct Node* head)
{
   map<Node*>mp
    while (head != NULL) 
    {
       
        if (mp.find(head) != mp.end())
        {
            return true;
        }
        mp.insert(head);
        head = head->next;
    }
    return false;
}

Ouput:

true

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments