Skip to content

Commit ceb8377

Browse files
committed
Loop in a LL
1 parent 1d3b178 commit ceb8377

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
struct Node {
5+
int data;
6+
struct Node* next;
7+
int flag;
8+
};
9+
10+
void push(struct Node** head_ref, int new_data)
11+
{
12+
struct Node* new_node = new Node;
13+
new_node->data = new_data;
14+
15+
new_node->flag = 0;
16+
new_node->next = (*head_ref);
17+
18+
(*head_ref) = new_node;
19+
}
20+
21+
bool detectLoop(struct Node* h)
22+
{
23+
while (h != NULL) {
24+
if (h->flag == 1)
25+
return true;
26+
27+
h->flag = 1;
28+
29+
h = h->next;
30+
}
31+
32+
return false;
33+
}
34+
35+
int main()
36+
{
37+
struct Node* head = NULL;
38+
39+
push(&head, 20);
40+
push(&head, 4);
41+
push(&head, 15);
42+
push(&head, 10);
43+
44+
head->next->next->next->next = head;
45+
46+
if (detectLoop(head))
47+
cout << "Loop found";
48+
else
49+
cout << "No Loop";
50+
51+
return 0;
52+
}
File renamed without changes.

0 commit comments

Comments
 (0)