Reverse a list using two pointers.
What to build
A list reversed by swapping, with no second list.
Requirements
- Read the numbers.
- Reverse the list with two pointers and swaps.
- Do not use slicing,
reverseorreversed.
Input
The first line has n. The second line has n whole numbers.
Output
The numbers reversed, separated by spaces.
Constraints
n is from 1 to 1000.
Example
Input:
3
1 2 3
Output:
3 2 1
Why it works
Each swap puts two items in their final places, so the pointers meet after half the list.
Examples
Example 1 · Input
3 1 2 3
Expected output
3 2 1
Example 2 · Input
1 7
Expected output
7
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Start one position at each end.
Hint 2
Swap, then move both towards the middle.
Solution
Show one correct solution (try it yourself first)
n = int(input())
nums = input().split()
i, j = 0, n - 1
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
print(" ".join(nums))