Middle Node
Completed
Build a list from n integers and print the middle value using the slow/fast pointer technique (for even lengths, the second of the two middle values).
Input
Line 1: n. Line 2: n integers.
Output
One integer.
Example
Input
5 1 2 3 4 5
Output
3
Editor
C
Hints
Move slow by one and fast by two; when fast reaches the end, slow is in the middle.
Solution explanation
The two-speed walk finds the middle in one pass without counting first.
Show solution
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
int main() {
int n, x;
struct Node *head = NULL, *tail = NULL;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
struct Node *node = malloc(sizeof(struct Node));
node->value = x;
node->next = NULL;
if (head == NULL) head = node;
else tail->next = node;
tail = node;
}
struct Node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
printf("%d\n", slow->value);
return 0;
}