COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
3.c
Go to the documentation of this file.
1#include "3.h"
2#include <stdio.h>
3
4double findAverageCycleLength(ListNode * arrPtr, int n) {
5 unsigned int totalCycleLength = 0;
6 for (int i = 0; i < n; i++) {
7 // For each list, we need to find the cycle length
8 // Floyd's cycle-fnding algorithm
9 ListNode * singleIncrement = &arrPtr[i];
10 ListNode * doubleIncrement = &arrPtr[i];
11 while (1) {
12 if (singleIncrement->next == NULL || doubleIncrement->next == NULL) {
13 break;
14 }
15 if (singleIncrement == doubleIncrement->next) {
16 // Cycle found
17 int cycleLength = 1;
18 ListNode * cycleIncrement = singleIncrement->next;
19 while (cycleIncrement != singleIncrement) {
20 cycleLength++;
21 cycleIncrement = cycleIncrement->next;
22 }
23 totalCycleLength += cycleLength;
24 break;
25 }
26 singleIncrement = singleIncrement->next;
27 doubleIncrement = doubleIncrement->next->next;
28 }
29 }
30 return (double) totalCycleLength / n;
31}
double findAverageCycleLength(ListNode *arrPtr, int n)
Definition 3.c:4
Definition 3.h:4
struct listNode * next
Definition 3.h:6