This repository has been archived by the owner on Oct 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathFloyd Algorithm.c
88 lines (77 loc) · 1.56 KB
/
Floyd Algorithm.c
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
int visited;
} SLL;
SLL *insert(SLL *head, int val)
{
if(head == NULL)
{
head = (SLL*) malloc(sizeof(SLL*));
head->data = val;
head->next = NULL;
head->visited = 0;
}
else {
SLL *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
SLL *new = (SLL*) malloc(sizeof(SLL*));
new->data = val;
new->next = NULL;
new->visited = 0;
temp->next = new;
}
return head;
}
void printList(SLL *head)
{
SLL*temp = head;
while(temp != NULL)
{
printf("%d -> ",temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int checkForCycles(SLL *head)
{
SLL *slow = head;
SLL *fast = head;
while(slow != NULL && fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
return 1;
}
}
return 0;
}
int main()
{
SLL *head = NULL;
head = insert(head, 10);
head = insert(head, 15);
head = insert(head, 20);
head = insert(head, 25);
head = insert(head, 30);
head = insert(head, 35);
head = insert(head, 40);
printList(head);
// head->next->next->next->next = head;
// Floyd algorithm
if(checkForCycles(head))
{
printf("Cycle is present in the list\n");
}
else {
printf("Cycle is not present in the list\n");
}
return 0;
}