// reverse a stack using recursion // loop constructs such as while or for loops are not allowed publicclassReverseStack{ publicstatic Stack<Character> stack = new Stack<>();
// insert a character x at the bottom of the stack publicstaticvoidinsertBottom(char x){ if(stack.empty()) { stack.push(x); }else { char a = stack.pop(); insertBottom(x); stack.push(a); } }
// reverse the given stack using insertAtBottom() publicstaticvoidreverse(){ if(stack.size() > 0) { char x = stack.pop(); reverse(); insertBottom(x); } }
To solve this problem, we need to make use of two function call stacks, one is for reverse method, and the other is for insertBottom method. The process is like this: https://www.youtube.com/watch?v=5lynUjiYXcU