Question: A stack is pushed into 1, 2, 3, 4, 5 in turn, then from the top of the stack to the bottom of the stack are 5, 4, 3, 2, 1 respectively. After transposing this stack, from the top of the stack to the bottom of the stack is 1, 2, 3, 4, 5, that is, the reverse order of the elements in the stack is realized, but it can only be realized by recursive functions, and no other data structures can be used.
1 // Only use recursive functions and stack operations to reverse a stack 2 #include <stdio.h> 3 #include " stack.h " // The header file contains the prototype declaration of stack operations and other related information 4 5 SqStack stack; 6 7 // Get the bottom element of the stack and delete 8 int getAndRemoveLastElement(SqStack * stack) 9 { 10 int result, last; 11 12 result = Pop(stack); 13 if (EmptyStack(*stack)) // The stack is empty, then return to the stack bottom element 14 { 15 return result; 16 } 17 else 18 { 19 last = getAndRemoveLastElement(stack); 20 Push(stack, result); // Re-push the previously popped element into the stack, at this time the first element of the stack is overwritten by the second element, which is quite Since the bottom element of the stack is deleted 21 return last; // The first element of the stack is returned 22 } 23 } 24 25 // The reverse stack 26 void reverse(SqStack * stack) 27 { 28 if (EmptyStack(* stack)) 29 { 30 return ; 31 } 32 int i = getAndRemoveLastElement(stack); // Get the element at the bottom of the stack and delete it from the stack 33 reverse(stack); // Call reverse recursively, the stack at this time is the stack with the element at the bottom of the stack deleted 34 Push( stack, i); // When the stack is empty, push the obtained bottom element into the stack 35 }