Created
December 16, 2018 02:14
-
-
Save nathanjackson/c538353f80fd5662db846b81d3a60feb to your computer and use it in GitHub Desktop.
Tortise and Hare Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <stddef.h> | |
#include <limits.h> | |
#include <stdio.h> | |
struct node { | |
int value; | |
struct node *next; | |
}; | |
void find_min(struct node *cur) { | |
assert(cur != NULL); | |
int minval = INT_MAX; | |
for (; cur != NULL; cur = cur->next) { | |
if (cur->value < minval) { | |
minval = cur->value; | |
} | |
} | |
printf("minval=%d\n", minval); | |
} | |
int has_cycle(struct node *head) { | |
if (head == NULL || head->next == NULL) { | |
return 0; | |
} | |
struct node *tortise, *hare; | |
tortise = head; | |
hare = head; | |
for (int i = 0; hare != NULL; i = i == INT_MAX ? 0 : i + 1) { | |
hare = hare->next; | |
if (i % 2) { | |
tortise = tortise->next; | |
} | |
if (hare == tortise) { | |
return 1; | |
} | |
} | |
return 0; | |
} | |
int main() { | |
struct node a, b, c, d; | |
a.next = &b; | |
b.next = &c; | |
c.next = &d; | |
d.next = &b; | |
printf("has cycle = %d\n", has_cycle(&a)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment