|
| 1 | +// C++ program to detect loop in a linked list |
| 2 | +#include <bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +/* Link list node */ |
| 6 | +struct Node { |
| 7 | + int data; |
| 8 | + struct Node* next; |
| 9 | +}; |
| 10 | + |
| 11 | +void push(struct Node** head_ref, int new_data) |
| 12 | +{ |
| 13 | + /* allocate node */ |
| 14 | + struct Node* new_node = new Node; |
| 15 | + |
| 16 | + /* put in the data */ |
| 17 | + new_node->data = new_data; |
| 18 | + |
| 19 | + /* link the old list off the new node */ |
| 20 | + new_node->next = (*head_ref); |
| 21 | + |
| 22 | + /* move the head to point to the new node */ |
| 23 | + (*head_ref) = new_node; |
| 24 | +} |
| 25 | + |
| 26 | +// Returns true if there is a loop in linked list |
| 27 | +// else returns false. |
| 28 | +bool detectLoop(struct Node* h) |
| 29 | +{ |
| 30 | + unordered_set<Node*> s; |
| 31 | + while (h != NULL) { |
| 32 | + // If this node is already present |
| 33 | + // in hashmap it means there is a cycle |
| 34 | + // (Because you will be encountering the |
| 35 | + // node for the second time). |
| 36 | + if (s.find(h) != s.end()) |
| 37 | + return true; |
| 38 | + |
| 39 | + // If we are seeing the node for |
| 40 | + // the first time, insert it in hash |
| 41 | + s.insert(h); |
| 42 | + |
| 43 | + h = h->next; |
| 44 | + } |
| 45 | + |
| 46 | + return false; |
| 47 | +} |
| 48 | + |
| 49 | +/* Driver program to test above function*/ |
| 50 | +int main() |
| 51 | +{ |
| 52 | + /* Start with the empty list */ |
| 53 | + struct Node* head = NULL; |
| 54 | + |
| 55 | + push(&head, 20); |
| 56 | + push(&head, 4); |
| 57 | + push(&head, 15); |
| 58 | + push(&head, 10); |
| 59 | + |
| 60 | + /* Create a loop for testing */ |
| 61 | + head->next->next->next->next = head; |
| 62 | + |
| 63 | + if (detectLoop(head)) |
| 64 | + cout << "Loop found"; |
| 65 | + else |
| 66 | + cout << "No Loop"; |
| 67 | + |
| 68 | + return 0; |
| 69 | +} |
| 70 | +// This code is contributed by Geetanjali |
0 commit comments