Guest User

Untitled

a guest
Dec 15th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. #include <assert.h>
  2. #include <stddef.h>
  3. #include <limits.h>
  4. #include <stdio.h>
  5.  
  6. struct node {
  7. int value;
  8. struct node *next;
  9. };
  10.  
  11. void find_min(struct node *cur) {
  12. assert(cur != NULL);
  13. int minval = INT_MAX;
  14. for (; cur != NULL; cur = cur->next) {
  15. if (cur->value < minval) {
  16. minval = cur->value;
  17. }
  18. }
  19. printf("minval=%d\n", minval);
  20. }
  21.  
  22. int has_cycle(struct node *head) {
  23. if (head == NULL || head->next == NULL) {
  24. return 0;
  25. }
  26. struct node *tortise, *hare;
  27. tortise = head;
  28. hare = head;
  29. for (int i = 0; hare != NULL; i = i == INT_MAX ? 0 : i + 1) {
  30. hare = hare->next;
  31. if (i % 2) {
  32. tortise = tortise->next;
  33. }
  34. if (hare == tortise) {
  35. return 1;
  36. }
  37. }
  38. return 0;
  39. }
  40.  
  41. int main() {
  42. struct node a, b, c, d;
  43.  
  44. a.next = &b;
  45. b.next = &c;
  46. c.next = &d;
  47. d.next = &b;
  48. printf("has cycle = %d\n", has_cycle(&a));
  49. }
Add Comment
Please, Sign In to add comment