It is clear that the statements before recursive statements run sequentially, while those after recursive statements run in reverse order.
Package recursion; import Java. util. stack; public class reverse_a_stack_using_recursion {/* input Stack: 3 2 1 Output Stack: 1 2 3 */public static void main (string [] ARGs) {stack <integer> S = new stack <integer> (); S. push (1); S. push (2); S. push (3); insertatbottom (S, 4); system. out. println (s); reversestack (s); system. out. println (s);} // Insert the item to the bottom of stack s public static void insertatbottom (stack <integer> S, int item) {If (S. isempty () {// If the stack is empty, s can be directly added. add (item); return;} int TMP = S. pop (); // Save the top element of the stack to TMP, which is converted to the substack problem insertatbottom (S, item) with one fewer element ); // recursively Insert the item into S. push (TMP); // insert TMP to the top of the stack again} // flip stack s public static void reversestack (stack <integer> S) {If (S. isempty () {return;} int TMP = S. pop (); // Save the top element of the stack to TMP, which is converted to the substack issue reversestack (s) with one fewer element ); // flip the remaining sub-stack insertatbottom (S, TMP); // insert TMP to the bottom of the stack }}
Http://www.geeksforgeeks.org/reverse-a-stack-using-recursion/
Recursively flip a stack reverse a stack using recursion