Skip to content

Commit ebc3bcf

Browse files
Linked list cycle
Signed-off-by: Leo Ma <[email protected]>
1 parent 1663c26 commit ebc3bcf

File tree

4 files changed

+106
-0
lines changed

4 files changed

+106
-0
lines changed

141_linked_list_cycle/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test list_cycle.c

141_linked_list_cycle/list_cycle.c

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <stdbool.h>
4+
5+
struct ListNode {
6+
int val;
7+
struct ListNode *next;
8+
};
9+
10+
static bool hasCycle(struct ListNode *head)
11+
{
12+
if (head == NULL || head->next == NULL) {
13+
return false;
14+
}
15+
16+
bool first = true;
17+
struct ListNode *p0, *p1;
18+
for (p0 = head, p1 = head; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) {
19+
if (p0 == p1 && !first) {
20+
return true;
21+
}
22+
first = false;
23+
}
24+
25+
return false;
26+
}
27+
28+
int main(int argc, char **argv)
29+
{
30+
int i, count = argc - 1;
31+
struct ListNode *head = NULL, *p, *prev;
32+
for (i = 0; i < count; i++) {
33+
p = malloc(sizeof(*p));
34+
p->val = atoi(argv[i + 1]);
35+
p->next = NULL;
36+
if (head == NULL) {
37+
head = p;
38+
} else {
39+
prev->next = p;
40+
}
41+
prev = p;
42+
}
43+
p->next = head;
44+
45+
printf("%s\n", hasCycle(head) ? "true" : "false");
46+
return 0;
47+
}

142_linked_list_cycle_ii/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test list_cycle.c
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <stdbool.h>
4+
5+
struct ListNode {
6+
int val;
7+
struct ListNode *next;
8+
};
9+
10+
static struct ListNode *detectCycle(struct ListNode *head)
11+
{
12+
if (head == NULL || head->next == NULL) {
13+
return false;
14+
}
15+
16+
bool first = true;
17+
struct ListNode *p0, *p1;
18+
for (p0 = head, p1 = head; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) {
19+
if (p0 == p1 && !first) {
20+
p0 = head;
21+
while (p0 != p1) {
22+
p0 = p0->next;
23+
p1 = p1->next;
24+
}
25+
return p0;
26+
}
27+
first = false;
28+
}
29+
30+
return NULL;
31+
}
32+
33+
int main(int argc, char **argv)
34+
{
35+
int i, count = argc - 1;
36+
struct ListNode *head = NULL, *p, *prev;
37+
for (i = 0; i < count; i++) {
38+
p = malloc(sizeof(*p));
39+
p->val = atoi(argv[i + 1]);
40+
p->next = NULL;
41+
if (head == NULL) {
42+
head = p;
43+
} else {
44+
prev->next = p;
45+
}
46+
prev = p;
47+
}
48+
p->next = head;
49+
50+
p = detectCycle(head);
51+
if (p != NULL) {
52+
printf("%d\n", p->val);
53+
}
54+
return 0;
55+
}

0 commit comments

Comments
 (0)