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)