The Wayback Machine - https://web.archive.org/web/20250321011234/https://www.geeksforgeeks.org/reverse-an-array-using-stack/
Open In App

Reverse an array using Stack

Last Updated : 16 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

For both iterative and recursive solutions, refer to the article on reverse an array. The time complexity is O(n), and the auxiliary space is O(1).

Approach: Using a custom stack – O(n) Time and O(n) Space

First, all elements of the array are pushed onto the stack. Since a stack follows the Last In, First Out (LIFO) principle, popping elements from the stack and storing them back into the array results in a reversed order. This efficiently reverses the array without using extra loops for swapping.

C++
#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(vector<int> &arr)
{
    int n = arr.size();

    // 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);
    }
    return;
}

// Driver Code
int main()
{

    vector<int> arr = {100, 200, 300, 400};

    int n = arr.size();
    reverseArray(arr);

    // Print array elements
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}
Java
import java.util.*;

class Stack {
    int size;

    // Stores index of top
    // element of a stack
    int top;
    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 GfG {

    // Function to reverse the array elements
    public static void reverse(int arr[])
    {
        int n = arr.length;

        // 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();
        }

        return;
    }

    // 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);
        for (int i = 0; i < n; i++) {
            System.out.print(a[i] + " ");
        }
    }
}
Python
class Stack:
    def __init__(self, capacity):
        self.capacity = capacity
        self.top = -1
        self.array = [0] * capacity

    # Function to check if the stack is full
    def isFull(self):
        return self.top == self.capacity - 1

    # Function to check if the stack is empty
    def isEmpty(self):
        return self.top == -1

    # Function to insert an element into the stack
    def push(self, item):
        if self.isFull():
            return
        self.top += 1
        self.array[self.top] = item

    # Function to remove an element from the stack
    def pop(self):
        if self.isEmpty():
            return -1
        item = self.array[self.top]
        self.top -= 1
        return item


# Function to reverse the array elements
def reverseArray(arr):
    n = len(arr)
    stack = Stack(n)

    # Push elements onto stack
    for i in range(n):
        stack.push(arr[i])

    # Pop elements back into the array (reversing it)
    for i in range(n):
        arr[i] = stack.pop()


# Driver Code
arr = [100, 200, 300, 400]
n = len(arr)
reverseArray(arr)

# Print reversed array
for i in arr:
    print(i, end= " ")
C#
using System;

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 GfG {
    // Function to reverse the array elements
    static void Reverse(int[] arr)
    {
        int n = arr.Length;
        // 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();
        }

        return;
    }

    // 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);
        // Print array elements
        for (int i = 0; i < n; i++) {
            Console.Write(a[i] + " ");
        }
    }
}
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)
{
    let n = arr.length;
    // 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);
    }
    return;
}

// Driver Code
function main()
{

    const arr = [ 100, 200, 300, 400 ];
    reverseArray(arr);
    // Print array elements
    console.log(arr.join(" "));
}

main();

Output
400 300 200 100 

Approach: Using STL inbuilt Stack- O(n) Time and O(n) Space

C++
#include <bits/stdc++.h>
using namespace std;

void reverse(vector<int> &arr)
{
    int n = arr.size();
    stack<int> st;

    // push all elements of array into stack
    for (int i = 0; i < n; i++)
    {
        st.push(arr[i]);
    }

    int i = 0;
    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++;
    }
    return;
}

// Driver Code
int main()
{
    vector<int> arr = {100, 200, 300, 400};
    reverse(arr);
    for (auto it : arr)
        cout << it << " ";
    return 0;
}
Java
import java.util.*;
class GfG {
    static void reverse(int arr[])
    {
        int n = arr.length;
        Stack<Integer> st = new 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++;
        }
        return;
    }

    // Driver function
    public static void main(String args[])
    {

        // Create a new array
        int[] a = new int[] { 100, 200, 300, 400 };

        // Call reverse method
        reverse(a);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }
}
Python
def reverse(arr):
    n = len(arr)
    st = []  

    # 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

    


# Driver Code
n = 4

# Create a new array
arr = [100, 200, 300, 400]

# Call reverse method
reverse(arr)
for i in range(n):
        print(arr[i], end=" ")
C#
using System;
using System.Collections.Generic;
class GfG {
    public static void Reverse(int[] arr)
    {
        int n = arr.Length;
        Stack<int> st = new Stack<int>();

        for (int i = 0; i < n; i++) {
            // Insert arr[i] into the stack
            st.Push(arr[i]);
        }

        // Reverse the array elements
        for (int i = 0; i < n; i++) {
            // Update arr[i]
            int top = st.Peek();

            st.Pop();

            arr[i] = top;
        }
        return;
    }

    // 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);
        // Print array elements
        for (int i = 0; i < n; i++) {
            Console.Write(a[i] + " ");
        }
    }
}
JavaScript
function reverse(arr)
{
    let n = arr.length;
    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++;
    }

    return;
}

// Driver Code
const n = 4;

// Create a new array
const arr = [ 100, 200, 300, 400 ];

// Call reverse method
reverse(arr);
// traverse the array to print all elements
console.log(arr.join(" "))

Output
400 300 200 100 




Next Article

Similar Reads

three90RightbarBannerImg