Розбір
Store the numbers in a linear array. Then print them in reverse order.
Let’s consider a solution for reversing an array using the two-pointer technique.
Set two variables and (we'll call them pointers):
at the beginning of the array ;
at the end of the array ;
Next, start a while loop, in which:
the values of and are swapped;
then is incremented by , and is decremented by ;
We continue the loop until the pointers and meet.
Note that the values of and can be swapped using an additional variable by performing three operations:
Algorithm realization
Read the input data.
scanf("%d",&n); for(i = 0; i < n; i++) scanf("%d",&mas[i]);
Print the numbers in the reverse order.
for(i = n - 1; i >= 0; i--) printf("%d ",mas[i]); printf("\n");
Algorithm realization — reverse the array
Declare an array.
#define MAX 110 int m[MAX];
Read the input data.
scanf("%d",&n); for(i = 1; i <= n; i++) scanf("%d",&m[i]);
Reverse the array using the two-pointer technique.
i = 1; j = n; while(i < j) { temp = m[i]; m[i] = m[j]; m[j] = temp; i++; j--; }
Print the numbers.
for(i = 1; i <= n; i++) printf("%d ",m[i]); printf("\n");
Algorithm realization – STL reverse
#include <cstdio> #include <vector> #include <algorithm> using namespace std; int n, i; vector<int> mas; int main(void) { scanf("%d",&n); mas.resize(n); for(i = 0; i < n; i++) scanf("%d",&mas[i]); reverse(mas.begin(),mas.end()); for(i = 0; i < n; i++) printf("%d ",mas[i]); printf("\n"); return 0; }
Java realization — print the array from right to left
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); int n = con.nextInt(); int mas[] = new int[n]; for(int i = 0; i < n; i++) mas[i] = con.nextInt(); for(int i = n - 1; i >= 0; i--) System.out.print(mas[i] + " "); System.out.println(); con.close(); } }
Java realization — reverse
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); int n = con.nextInt(); int m[] = new int[n]; // Read data for(int i = 0; i < n; i++) m[i] = con.nextInt(); // Reverse an array int i = 0, j = n - 1; while(i < j) { int temp = m[i]; m[i] = m[j]; m[j] = temp; i++; j--; } // Print the reversed array for(i = 0; i < n; i++) System.out.print(m[i] + " "); System.out.println(); con.close(); } }
Python realization
Read the input data.
n = int(input()) lst = list(map(int, input().split()))
Print the numbers in the reverse order.
for i in range(n - 1,-1,-1): print(lst[i], end = " ")
Python realization — reverse
Read the input data.
n = int(input()) lst = list(map(int, input().split()))
Reverse the list using the reverse function.
lst.reverse()
Print the reversed list.
print(*lst)