Friday, September 11, 2015

Reverse Array Using Stack in Java

Stack can be used to reverse an array.

import java.util.Arrays;
import java.util.Stack;

public class ReverseArrayUsingStack {

 public static int[] reverse(int[] data) {

  Stack<Integer> stack = new Stack<Integer>();

  for (int i = 0; i < data.length; i++)
   stack.push(data[i]);

  for (int i = 0; i < data.length; i++)
   data[i] = stack.pop();

  return data;
 }

 public static void main(String[] args) {

  int[] a = { 41, 2, 151, 13, 43, 12 };

  System.out.println(Arrays.toString(a));

  System.out.println(Arrays.toString(reverse(a)));

 }
}


Initially push all the elements in the array onto the Stack. Stack is now full of items. Then pop all the elements from Stack back into original array.

In this solution, algorithm is not very efficient in terms of space because it uses an extra data structure to hold the items.


No comments:

Post a Comment