forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycle_detect_ll.c
More file actions
28 lines (24 loc) · 716 Bytes
/
cycle_detect_ll.c
File metadata and controls
28 lines (24 loc) · 716 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <stdlib.h>
struct Node {int data; struct Node *next;};
struct Node* newNode(int val){
struct Node* n = malloc(sizeof(struct Node));
n->data = val; n->next = NULL; return n;
}
int hasCycle(struct Node* head){
struct Node *slow = head, *fast = head;
while (fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return 1;
}
return 0;
}
int main(){
struct Node *head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = head->next; // cycle
printf(hasCycle(head) ? "Cycle detected\n" : "No cycle\n");
}