-
Notifications
You must be signed in to change notification settings - Fork 1
/
ll_cycle.c
77 lines (66 loc) · 2.45 KB
/
ll_cycle.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
#include <stdio.h>
#define FALSE 0;
#define TRUE 1;
// 链表闭环判断 Floyd's Tortoise and Hare
typedef struct node {
int value;
struct node *next;
} node;
int ll_has_cycle(node *head) {
if (head == NULL) return FALSE;
node *tortoise = head;
if (tortoise->next == NULL) return FALSE;
node *hare = tortoise->next;
while(tortoise != NULL && hare != NULL) {
if (tortoise == hare) {
return TRUE;
} else {
tortoise = tortoise->next;
if (hare->next == NULL) {
return FALSE;
}
hare = hare->next->next;
}
}
return FALSE;
}
void test_ll_has_cycle(void) {
int i;
node nodes[25]; //enough to run our tests
for(i=0; i < sizeof(nodes)/sizeof(node); i++) {
nodes[i].next = 0;
nodes[i].value = 0;
}
nodes[0].next = &nodes[1];
nodes[1].next = &nodes[2];
nodes[2].next = &nodes[3];
printf("Checking first list for cycles. There should be none, ll_has_cycle says it has %s cycle\n", ll_has_cycle(&nodes[0])?"a":"no");
nodes[4].next = &nodes[5];
nodes[5].next = &nodes[6];
nodes[6].next = &nodes[7];
nodes[7].next = &nodes[8];
nodes[8].next = &nodes[9];
nodes[9].next = &nodes[10];
nodes[10].next = &nodes[4];
printf("Checking second list for cycles. There should be a cycle, ll_has_cycle says it has %s cycle\n", ll_has_cycle(&nodes[4])?"a":"no");
nodes[11].next = &nodes[12];
nodes[12].next = &nodes[13];
nodes[13].next = &nodes[14];
nodes[14].next = &nodes[15];
nodes[15].next = &nodes[16];
nodes[16].next = &nodes[17];
nodes[17].next = &nodes[14];
printf("Checking third list for cycles. There should be a cycle, ll_has_cycle says it has %s cycle\n", ll_has_cycle(&nodes[11])?"a":"no");
nodes[18].next = &nodes[18];
printf("Checking fourth list for cycles. There should be a cycle, ll_has_cycle says it has %s cycle\n", ll_has_cycle(&nodes[18])?"a":"no");
nodes[19].next = &nodes[20];
nodes[20].next = &nodes[21];
nodes[21].next = &nodes[22];
nodes[22].next = &nodes[23];
printf("Checking fifth list for cycles. There should be none, ll_has_cycle says it has %s cycle\n", ll_has_cycle(&nodes[19])?"a":"no");
printf("Checking length-zero list for cycles. There should be none, ll_has_cycle says it has %s cycle\n", ll_has_cycle(NULL)?"a":"no");
}
int main(void) {
test_ll_has_cycle();
return 0;
}