Reverse with Two Pointers
Completed
Write void reverse(int *a, int n) that uses two pointers, left (starting at the first element) and right (moved to the last one), swapping and moving them towards each other n/2 times. Reverse an input array and print it.
Input
Line 1: n. Line 2: n integers.
Output
One line.
Example
Input
5 1 2 3 4 5
Output
5 4 3 2 1
Editor
C
Hints
Move right to the last element with right++ (n - 1 times).
Swap through the pointers, then move them inwards.
Solution explanation
Two pointers walking towards each other is a classic technique for reversing and pair-finding.
Show solution
#include <stdio.h>
void reverse(int *a, int n) {
int *left = a;
int *right = a;
for (int i = 0; i < n - 1; i++) right++;
for (int i = 0; i < n / 2; i++) {
int t = *left;
*left = *right;
*right = t;
left++;
right--;
}
}
int main() {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
reverse(a, n);
for (int i = 0; i < n; i++) printf("%d%s", a[i], i < n - 1 ? " " : "\n");
return 0;
}