There is no free lunch in the world. This topic comes from the Cattle network: http://www.nowcoder.com/773456
Topic: Given a stack, without other data structure assistance, the stack content reverse.
Assuming that other data structures are allowed, we can quickly think of using a different stack to "pour" the contents of the original stack into another stack.
But Zhoecheng teacher said, not allowed.
The essence of recursion is the use of stacks. So we can use recursion to let the system create such a "secondary stack" for us
Talk is cheap, this is the code:
1 Public Static voidReversestack (stack<integer>stack) {2 if(Stack.isempty ())return;3 inttemp =getbottomdata (stack);4 reversestack (stack);5 Stack.push (temp);6 }7 8 Public Static intGetbottomdata (stack<integer>stack) {9 intres =Stack.pop ();Ten if(Stack.isempty ()) { One returnRes; A } - inttemp =getbottomdata (stack); - Stack.push (res); the returntemp; -}
The function of these two functions can be known by the name of the functor.
The core function is: Getbottomdata (stack<integer> Stack), the recursive invocation process is illustrated as follows:
Along the recursive process, it can be found that the function of the Getbottomdata (stack<integer> stack) function is to return the stack bottom element, and the original stack data to the bottom of the stack to move.
As shown, after a single action, the original stack [4, 3, 2, 1] pops the bottom element 1, and the stack's length is reduced by 1.
Next, explain the Reversestack (stack<integer> Stack) function.
The recursive thinking of this function is relatively simple, each layer recursively through the getbottomdata () to the bottom of the stack of the elements out and cached into the variable, until the stack empty, and then began to reverse the value of each layer variable into the stack, and finally the original stack of data is stored in reverse order. The recursive invocation process is as follows:
Record, summarize, ascend.
Reverse the stack with a recursive function