Array obtained by repeatedly reversing array after every insertion from given array | Java program of the above approach ; Function to generate the array by inserting array elements one by one followed by reversing the array ; Doubly ended Queue ; Iterate over the array ; Push array elements alternately to the front and back ; If size of list is odd ; Reverse the list ; Print the elements of the array ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static void generateArray ( int arr [ ] , int n ) { Deque < Integer > ans = new LinkedList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( i & 1 ) != 0 ) ans . addFirst ( arr [ i ] ) ; else ans . add ( arr [ i ] ) ; } if ( ( n & 1 ) != 0 ) { Collections . reverse ( Arrays . asList ( ans ) ) ; } for ( int x : ans ) { System . out . print ( x + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int n = 4 ; int arr [ ] = { 1 , 2 , 3 , 4 } ; generateArray ( arr , n ) ; } }