Tuesday, June 21, 2016

Reverse stack using recursion in java

 Here I am going to implement stack with fixed size of array and it also has behavior that will reverse the stack data.  
 package com.raj;  
 /**  
  * @author rajendar.bit@gmail.com  
  *  
  */  
 public class Stack<T> {  
  private Object stack[];  
  private int capacity;  
  private int index;  
  private final static int DEFAULT_SIZE=10;  
  public Stack(){  
  this(DEFAULT_SIZE);  
  }  
  public Stack(int capacity){  
  this.capacity = capacity;  
  stack = new Object[capacity];  
  }  
  /**  
  *  
  * @return boolean  
  */  
  public boolean isEmpty(){  
  return this.index==0;  
  }  
  /**  
  *  
  * @return boolean  
  */  
  public boolean isFull(){  
  return this.capacity==this.index;  
  }  
  /**  
  * <p>This method will be used to push the data at top.<p>  
  * @param t  
  */  
  public void push(T t){  
  if(isFull())  
   throw new IllegalArgumentException("Stack over flow.");  
  stack[index++]=t;  
  }  
  /**  
  * <p>This method will return and remove the top element.<p>  
  * @return  
  */  
  @SuppressWarnings("unchecked")  
  public T pop(){  
  if(isEmpty())  
   throw new IllegalArgumentException("stack under flow.");  
   T t= (T)stack[--index];  
   stack[index] = null;  
   return t;  
  }  
  /**  
  * <p>This method will reverse the existing stack recursively.<p>  
  * @param size  
  */  
  public void reverse(int size){  
  if(size==0){  
   return;  
  }  
  T t = pop();  
  reverse(size-1);  
  inserAtBottom(t);  
  }  
  /**  
  * <p>This method returns number of elements in stack.<p>  
  * @return  
  */  
  public int size(){  
  return index;  
  }  
  /**  
  * <p>Inserts the element at bottom in existing stack.<p>  
  * @param t  
  */  
  private void inserAtBottom(T t){  
  if(isEmpty()){  
   push(t);  
  }else{  
   T tmp = pop();  
   inserAtBottom(t);  
   push(tmp);  
  }  
  }  
 }  
 Main method:  
 package com.raj;  
 /**  
  * @author rajendar.bit@gmail.com  
  *  
  */  
 public class StackMain{  
  public static void main(String[] args) {  
  Stack<Integer> stack = new Stack<>();  
  for (int i = 0; i < 10; i++) {  
   stack.push(i);  
  }  
  stack.reverse(stack.size());  
  while(stack.size()!=0){  
   System.out.println(stack.pop());  
  }  
  Stack<String> stacks = new Stack<>();  
  stacks.push("A");  
  stacks.push("B");  
  stacks.push("C");  
  stacks.reverse(stacks.size());  
  while(stacks.size()!=0){  
   System.out.println(stacks.pop());  
  }  
  }  
 }