-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloopinlinkedlist.c
63 lines (49 loc) · 941 Bytes
/
loopinlinkedlist.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
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
int countNodes(struct Node *n)
{
int res = 1;
struct Node *temp = n;
while (temp->next != n)
{
res++;
temp = temp->next;
}
return res;
}
int countNodesinLoop(struct Node *list)
{
struct Node *slow_p = list, *fast_p = list;
while (slow_p && fast_p && fast_p->next)
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
if (slow_p == fast_p)
return countNodes(slow_p);
}
return 0;
}
struct Node *newNode(int key)
{
struct Node *temp =
(struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
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 = newNode(5);
head->next->next->next->next->next = head->next;
printf("%d \n", countNodesinLoop(head));
return 0;
}