Skip to content

Commit

Permalink
Linked list cycle
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Oct 27, 2017
1 parent 1663c26 commit ebc3bcf
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 141_linked_list_cycle/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test list_cycle.c
47 changes: 47 additions & 0 deletions 141_linked_list_cycle/list_cycle.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct ListNode {
int val;
struct ListNode *next;
};

static bool hasCycle(struct ListNode *head)
{
if (head == NULL || head->next == NULL) {
return false;
}

bool first = true;
struct ListNode *p0, *p1;
for (p0 = head, p1 = head; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) {
if (p0 == p1 && !first) {
return true;
}
first = false;
}

return false;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
struct ListNode *head = NULL, *p, *prev;
for (i = 0; i < count; i++) {
p = malloc(sizeof(*p));
p->val = atoi(argv[i + 1]);
p->next = NULL;
if (head == NULL) {
head = p;
} else {
prev->next = p;
}
prev = p;
}
p->next = head;

printf("%s\n", hasCycle(head) ? "true" : "false");
return 0;
}
2 changes: 2 additions & 0 deletions 142_linked_list_cycle_ii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test list_cycle.c
55 changes: 55 additions & 0 deletions 142_linked_list_cycle_ii/list_cycle.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct ListNode {
int val;
struct ListNode *next;
};

static struct ListNode *detectCycle(struct ListNode *head)
{
if (head == NULL || head->next == NULL) {
return false;
}

bool first = true;
struct ListNode *p0, *p1;
for (p0 = head, p1 = head; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) {
if (p0 == p1 && !first) {
p0 = head;
while (p0 != p1) {
p0 = p0->next;
p1 = p1->next;
}
return p0;
}
first = false;
}

return NULL;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
struct ListNode *head = NULL, *p, *prev;
for (i = 0; i < count; i++) {
p = malloc(sizeof(*p));
p->val = atoi(argv[i + 1]);
p->next = NULL;
if (head == NULL) {
head = p;
} else {
prev->next = p;
}
prev = p;
}
p->next = head;

p = detectCycle(head);
if (p != NULL) {
printf("%d\n", p->val);
}
return 0;
}

0 comments on commit ebc3bcf

Please sign in to comment.