import java.util.Stack;
/**
* Inplace reversal of Stack
* @author Prateek
*/
class ReverseStackRecursion {
/**
* Subroutine to Reverse the element of stack
* @param stack : input stack
*/
public void reverseStack(Stack<Integer> stack){
if(stack.isEmpty())
return ;
int val= stack.pop();
reverseStack(stack);
pushToBottom(stack,val);
return ;
}
/**
* Pushes the incoming element or item to the bottom of the stack
*/
private void pushToBottom(Stack<Integer> stack,int item){
if(stack.isEmpty()){
stack.push(item);
return ;
}
int val= stack.pop();
pushToBottom(stack,item);
stack.push(val);
}
public static void main
(String[] args
) { ReverseStackRecursion obj=new ReverseStackRecursion();
Stack<Integer> stack=new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
obj.reverseStack(stack);
}
}
CmltcG9ydCBqYXZhLnV0aWwuU3RhY2s7Ci8qKgogKiAgSW5wbGFjZSByZXZlcnNhbCBvZiBTdGFjawogKiBAYXV0aG9yIFByYXRlZWsKICovCiBjbGFzcyBSZXZlcnNlU3RhY2tSZWN1cnNpb24gewoKCS8qKgoJICogU3Vicm91dGluZSB0byBSZXZlcnNlIHRoZSBlbGVtZW50IG9mIHN0YWNrCQoJICogQHBhcmFtIHN0YWNrIDogaW5wdXQgc3RhY2sKCSAqLwoJcHVibGljIHZvaWQgcmV2ZXJzZVN0YWNrKFN0YWNrPEludGVnZXI+IHN0YWNrKXsKCQlpZihzdGFjay5pc0VtcHR5KCkpCgkJCXJldHVybiA7CgoJCWludCB2YWw9IHN0YWNrLnBvcCgpOwoJCXJldmVyc2VTdGFjayhzdGFjayk7CgoJCXB1c2hUb0JvdHRvbShzdGFjayx2YWwpOwoJCXJldHVybiA7Cgl9CgoJLyoqCgkgKiBQdXNoZXMgdGhlIGluY29taW5nIGVsZW1lbnQgb3IgaXRlbSB0byB0aGUgYm90dG9tIG9mIHRoZSBzdGFjawkKCSAqLwoJcHJpdmF0ZSB2b2lkIHB1c2hUb0JvdHRvbShTdGFjazxJbnRlZ2VyPiBzdGFjayxpbnQgaXRlbSl7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