Reverse an array using Stack
Given an array arr[] of size N, the task to reverse the array using Stack.
Examples:
Input: arr[] = { 10, 20, 30, 40, 50 } Output: 50 40 30 20 10 Explanation: Reversing the array modifies arr[] to { 50, 40, 30, 20, 10 } Therefore, the required output is 50 40 30 20 10.
Input: arr[] = { 1 } Output: 1
Iterative and Recursive Approach: Refer the article reverse an array to solve this problem iteratively or recursively. Time Complexity: O(N) Auxiliary Space: O(1)
Stack-based Approach: Follow the steps below to solve the problem:
- Initialize a Stack to store the array elements.
- Traverse the array and push all the array elements into the stack.
- Finally, print the array.
Below is the implementation of the above approach
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Structure of stack class Stack { public : // Stores index of top // element of a stack int top; // Stores maximum count of // elements stored in a stack unsigned capacity; // Stores address of // array element int * array; }; // Function to Initialize a stack // of given capacity. Stack* createStack(unsigned capacity) { Stack* stack = new Stack(); stack->capacity = capacity; stack->top = -1; stack->array = new int [(stack->capacity * sizeof ( int ))]; return stack; } // Function to check if // the stack is full or not int isFull(Stack* stack) { return stack->top == stack->capacity - 1; } // Function to check if // the stack is empty or not int isEmpty(Stack* stack) { return stack->top == -1; } // Function to insert an element // into the stack. void push(Stack* stack, int item) { // If stack is full if (isFull(stack)) return ; // Insert element into stack stack->array[++stack->top] = item; } // Function to remove an element // from stack. int pop(Stack* stack) { // If stack is empty if (isEmpty(stack)) return -1; // Pop element from stack return stack->array[stack->top--]; } // Function to reverse the array elements void reverseArray( int arr[], int n) { // Initialize a stack of capacity n Stack* stack = createStack(n); for ( int i = 0; i < n; i++) { // Insert arr[i] into the stack push(stack, arr[i]); } // Reverse the array elements for ( int i = 0; i < n; i++) { // Update arr[i] arr[i] = pop(stack); } // Print array elements for ( int i = 0; i < n; i++) cout << arr[i] << " " ; } // Driver Code int main() { int arr[] = { 100, 200, 300, 400 }; int N = sizeof (arr) / sizeof (arr[0]); reverseArray(arr, N); return 0; } |
C
// C program to implement // the above approach #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // Structure of stack struct Stack { // Stores index of top // element of a stack int top; // Stores maximum count of // elements stored in a stack unsigned capacity; // Stores address of // array element int * array; }; // Function to Initialize a stack // of given capacity. struct Stack* createStack(unsigned capacity) { struct Stack* stack = ( struct Stack*) malloc ( sizeof ( struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = ( int *) malloc ( stack->capacity * sizeof ( int )); return stack; } // Function to check if // the stack is full or not int isFull( struct Stack* stack) { return stack->top == stack->capacity - 1; } // Function to check if // the stack is empty or not int isEmpty( struct Stack* stack) { return stack->top == -1; } // Function to insert an element // into the stack. void push( struct Stack* stack, int item) { // If stack is full if (isFull(stack)) return ; // Insert element into stack stack->array[++stack->top] = item; } // Function to remove an element // from stack. int pop( struct Stack* stack) { // If stack is empty if (isEmpty(stack)) return -1; // Pop element from stack return stack->array[stack->top--]; } // Function to reverse the array elements void reverseArray( int arr[], int n) { // Initialize a stack of capacity n struct Stack* stack = createStack(n); for ( int i = 0; i < n; i++) { // Insert arr[i] into the stack push(stack, arr[i]); } // Reverse the array elements for ( int i = 0; i < n; i++) { // Update arr[i] arr[i] = pop(stack); } // Print array elements for ( int i = 0; i < n; i++) printf ( "%d " , arr[i]); } // Driver Code int main() { int arr[] = { 100, 200, 300, 400 }; int N = sizeof (arr) / sizeof (arr[0]); reverseArray(arr, N); return 0; } |
Java
// Java program to implement // the above approach import java.util.*; // Structure of stack class Stack { // Stores maximum count of // elements stored in a stack int size; // Stores index of top // element of a stack int top; // Stores address of // array element int [] a; // Function to check if // the stack is empty or not boolean isEmpty() { return (top < 0 ); } // Function to Initialize // a stack of given capacity. Stack( int n) { top = - 1 ; size = n; a = new int [size]; } // Function to push // an element into Stack boolean push( int x) { // If Stack is full if (top >= size) { System.out.println( "Stack Overflow" ); return false ; } else { // Insert element // into stack a[++top] = x; return true ; } } // Function to remove an element // from stack. int pop() { // If stack is empty if (top < 0 ) { System.out.println( "Stack Underflow" ); return 0 ; } // Pop element from stack else { int x = a[top--]; return x; } } } // Driver Code class Main { // Function to reverse the array elements public static void reverse( int arr[], int n) { // Initialize a stack of capacity n Stack obj = new Stack(n); for ( int i = 0 ; i < n; i++) { // Insert arr[i] into the stack obj.push(arr[i]); } // Reverse the array elements for ( int i = 0 ; i < n; i++) { // Update arr[i] arr[i] = obj.pop(); } // Print array elements for ( int i = 0 ; i < n; i++) { System.out.print(arr[i] + " " ); } } // Driver function public static void main(String args[]) { int n = 4 ; // Create a new array int [] a = new int [] { 100 , 200 , 300 , 400 }; // Call reverse method reverse(a, n); } } |
C#
using System; // Structure of stack class Stack { // Stores maximum count of // elements stored in a stack int size; // Stores index of top // element of a stack int top; // Stores address of // array element int [] a; // Function to check if // the stack is empty or not public bool IsEmpty() { return (top < 0); } // Function to Initialize // a stack of given capacity. public Stack( int n) { top = -1; size = n; a = new int [size]; } // Function to push // an element into Stack public bool Push( int x) { // If Stack is full if (top >= size) { Console.WriteLine( "Stack Overflow" ); return false ; } else { // Insert element // into stack a[++top] = x; return true ; } } // Function to remove an element // from stack. public int Pop() { // If stack is empty if (top < 0) { Console.WriteLine( "Stack Underflow" ); return 0; } // Pop element from stack else { int x = a[top--]; return x; } } } // Driver Code class MainClass { // Function to reverse the array elements public static void Reverse( int [] arr, int n) { // Initialize a stack of capacity n Stack obj = new Stack(n); for ( int i = 0; i < n; i++) { // Insert arr[i] into the stack obj.Push(arr[i]); } // Reverse the array elements for ( int i = 0; i < n; i++) { // Update arr[i] arr[i] = obj.Pop(); } // Print array elements for ( int i = 0; i < n; i++) { Console.Write(arr[i] + " " ); } } // Driver function public static void Main() { int n = 4; // Create a new array int [] a = new int [] { 100, 200, 300, 400 }; // Call reverse method Reverse(a, n); } } |
Javascript
// JavaScript program to implement // the above approach // Structure of stack class Stack { constructor(capacity) { // Stores index of top // element of a stack this .top = -1; // Stores maximum count of // elements stored in a stack this .capacity = capacity; // Stores address of // array element this .array = new Array(capacity); } } // Function to check if // the stack is full or not function isFull(stack) { return stack.top == stack.capacity - 1; } // Function to check if // the stack is empty or not function isEmpty(stack) { return stack.top == -1; } // Function to insert an element // into the stack. function push(stack, item) { // If stack is full if (isFull(stack)) return ; // Insert element into stack stack.array[++stack.top] = item; } // Function to remove an element // from stack. function pop(stack) { // If stack is empty if (isEmpty(stack)) return -1; // Pop element from stack return stack.array[stack.top--]; } // Function to reverse the array elements function reverseArray(arr, n) { // Initialize a stack of capacity n const stack = new Stack(n); for (let i = 0; i < n; i++) { // Insert arr[i] into the stack push(stack, arr[i]); } // Reverse the array elements for (let i = 0; i < n; i++) { // Update arr[i] arr[i] = pop(stack); } // Print array elements console.log(arr.join( ' ' )); } // Driver Code function main() { const arr = [100, 200, 300, 400]; const N = arr.length; reverseArray(arr, N); } main(); |
Output
400 300 200 100
Approach 2: Using STL
To minimize the code we can simply use the STL Stack ( #include <stack> )
C++
// Online C++ compiler to run C++ program online #include <iostream> #include <stack> // including Stack ( push, pop, empty, size... etc) using namespace std; void reverse( int arr[] , int n){ stack< int >st; // make stack containing intergers // push all elements of array into stack for ( int i=0 ;i<n ;i++){ st.push(arr[i]); } // to update elements of array of ith index int i=0; // run loop until stack not empty while (!st.empty()){ // get top element of stack and pop it int top = st.top(); st.pop(); // update ith index of array arr[i] = top; // increment i i++; } // traverse the array to print all elements for ( int i=0 ;i<n ;i++){ cout << arr[i] << " " ; } return ; } // Driver Code int main() { int n = 4; // Create a new array int arr[] ={ 100, 200, 300, 400 }; // Call reverse method reverse(arr, n); return 0; } // this code is contributed by bhardwajji |
Java
// Java program to implement // the above approach import java.util.*; class Main { // Function to reverse the array elements public static void reverse( int arr[], int n) { Stack<Integer> st = new Stack<>(); // make stack containing intergers // push all elements of array into stack for ( int i= 0 ;i<n ;i++){ st.push(arr[i]); } // to update elements of array of ith index int i= 0 ; // run loop until stack not empty while (st.empty()== false ){ // get top element of stack and pop it int top = st.peek(); st.pop(); // update ith index of array arr[i] = top; // increment i i++; } // traverse the array to print all elements for (i= 0 ;i<n ;i++){ System.out.print(arr[i]+ " " ); } } // Driver function public static void main(String args[]) { int n = 4 ; // Create a new array int [] a = new int [] { 100 , 200 , 300 , 400 }; // Call reverse method reverse(a, n); } } //This code is contributed by shubhamrajput6156 |
Python3
# Python3 program to implement the above approach def reverse(arr, n): st = [] # make stack containing intergers # push all elements of array into stack for i in range (n): st.append(arr[i]) # to update elements of array of ith index i = 0 # run loop until stack not empty while ( len (st) > 0 ): # get top element of stack and pop it top = st.pop() # update ith index of array arr[i] = top # increment i i + = 1 # traverse the array to print all elements for i in range (n): print (arr[i], end = " " ) # Driver Code n = 4 # Create a new array arr = [ 100 , 200 , 300 , 400 ] # Call reverse method reverse(arr, n) # this code is contributed by Abhijeet Kumar(abhijeet19403) |
Javascript
function reverse(arr, n) { const st = []; // make stack containing intergers // push all elements of array into stack for (let i = 0; i < n; i++) { st.push(arr[i]); } // to update elements of array of ith index let i = 0; // run loop until stack not empty while (st.length) { // get top element of stack and pop it const top = st.pop(); // update ith index of array arr[i] = top; // increment i i++; } // traverse the array to print all elements for (let i = 0; i < n; i++) { console.log(arr[i] + " " ); } } // Driver Code const n = 4; // Create a new array const arr = [100, 200, 300, 400]; // Call reverse method reverse(arr, n); |
Output
400 300 200 100
Time Complexity: O(N)
Auxiliary Space: O(N)
Please Login to comment...