fork download
  1.  
  2. import java.util.Stack;
  3. /**
  4.  * Inplace reversal of Stack
  5.  * @author Prateek
  6.  */
  7. class ReverseStackRecursion {
  8.  
  9. /**
  10. * Subroutine to Reverse the element of stack
  11. * @param stack : input stack
  12. */
  13. public void reverseStack(Stack<Integer> stack){
  14. if(stack.isEmpty())
  15. return ;
  16.  
  17. int val= stack.pop();
  18. reverseStack(stack);
  19.  
  20. pushToBottom(stack,val);
  21. return ;
  22. }
  23.  
  24. /**
  25. * Pushes the incoming element or item to the bottom of the stack
  26. */
  27. private void pushToBottom(Stack<Integer> stack,int item){
  28. if(stack.isEmpty()){
  29. stack.push(item);
  30. return ;
  31. }
  32.  
  33. int val= stack.pop();
  34. pushToBottom(stack,item);
  35. stack.push(val);
  36. }
  37.  
  38. public static void main(String[] args) {
  39. ReverseStackRecursion obj=new ReverseStackRecursion();
  40. Stack<Integer> stack=new Stack<Integer>();
  41. stack.push(1);
  42. stack.push(2);
  43. stack.push(3);
  44. stack.push(4);
  45.  
  46. System.out.println(stack);
  47. obj.reverseStack(stack);
  48.  
  49. System.out.println(stack);
  50. }
  51. }
  52.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
[1, 2, 3, 4]
[4, 3, 2, 1]