File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Data_Structure/src/Linked Lists Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ // This algorithm is used to find a loop in a linked list. It uses two pointers one moving twice
2+ // as fast as the other one. The faster one is called the faster pointer and the other one is
3+ // called the slow pointer.
4+
5+ #include <bits/stdc++.h>
6+ using namespace std;
7+
8+ /* Link list node */
9+ class Node {
10+ public:
11+ int data;
12+ Node* next;
13+ };
14+
15+ void push(Node** head_ref, int new_data)
16+ {
17+ /* allocate node */
18+ Node* new_node = new Node();
19+
20+ /* put in the data */
21+ new_node->data = new_data;
22+
23+ /* link the old list off the new node */
24+ new_node->next = (*head_ref);
25+
26+ /* move the head to point to the new node */
27+ (*head_ref) = new_node;
28+ }
29+
30+ int detectLoop(Node* list)
31+ {
32+ Node *slow_p = list, *fast_p = list;
33+
34+ while (slow_p && fast_p && fast_p->next) {
35+ slow_p = slow_p->next;
36+ fast_p = fast_p->next->next;
37+ if (slow_p == fast_p) {
38+ return 1;
39+ }
40+ }
41+ return 0;
42+ }
43+
44+ /* Driver code*/
45+ int main()
46+ {
47+ /* Start with the empty list */
48+ Node* head = NULL;
49+
50+ push(&head, 20);
51+ push(&head, 4);
52+ push(&head, 15);
53+ push(&head, 10);
54+
55+ /* Create a loop for testing */
56+ head->next->next->next->next = head;
57+ if (detectLoop(head))
58+ cout << "Loop Found";
59+ else
60+ cout << "No Loop";
61+ return 0;
62+ }
63+
64+ Time complexity: O(N).
65+ Auxiliary Space: O(1).
You can’t perform that action at this time.
0 commit comments