-
Notifications
You must be signed in to change notification settings - Fork 118
/
141.c
60 lines (45 loc) · 1.14 KB
/
141.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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct ListNode {
int val;
struct ListNode *next;
};
bool hasCycle(struct ListNode *head) {
if (head == NULL) return false;
struct ListNode *fast, *slow;
fast = slow = head;
while (fast && slow) {
if (fast) fast = fast->next;
if (fast) fast = fast->next;
if (slow) slow = slow->next;
if (fast == slow && slow != NULL) return true;
}
return false;
}
int main() {
struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode));
struct ListNode *p = l1;
p->val = 1;
p->next = l1 + 1;
p = p->next;
p->val = 2;
p->next = l1 + 2;
p = p->next;
p->val = 3;
p->next = l1 + 3;
p = p->next;
p->val = 4;
p->next = l1 + 4;
p = p->next;
p->val = 5;
p->next = NULL; /* no cycle */
printf("%d\n", hasCycle(l1));
/* no cycle */
printf("%d\n", hasCycle(l1 + 4));
p->next = l1 + 2; /* cycle */
printf("%d\n", hasCycle(l1));
/* no cycle */
printf("%d\n", hasCycle(NULL));
return 0;
}