Practice #2
Lesson 11 of 14 in Coddy's Linked List - Data Structures Series #5 course.
Challenge
EasyWrite a function findMiddle that gets an integer array arr (the values of a linked list) and returns the middle value.
For odd lengths, the exact middle. For even lengths, the second of the two middle nodes (index length / 2). If the list is empty, return -1.
Use a linked list to solve this problem! The classic approach is two pointers: a slow one and a fast one. When the fast pointer reaches the end, the slow one is at the middle.
You must use the LinkedList class (provided in linkedlist.<ext> along with node.<ext>) — do not use language built-ins like arrays' built-in reverse, slicing, or stdlib list operations to compute the result.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"
int main() {
char line[8192];
if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
int arr[4096];
int len = 0;
char* tok = strtok(line, " \t\r\n");
while (tok) { arr[len++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
int r = findMiddle(arr, len);
printf("%d\n", r);
return 0;
}