Both of these operations are recursive implementations, Hanoi thought.
1. Reverse Stack
void Reversestack (stack& stack) { if (stack. Count = = 0) return; Object top = stack. Pop (); Reversestack (stack); if (stack. Count = = 0) { stack. Push (top); return; } Object TOP2 = stack. Pop (); Reversestack (stack); P1 Stack. Push (top); Reversestack (stack); P2 stack. Push (TOP2); }
Example:
such as stacks
1
2 Object top = stack. Pop (); Post stack becomes 2
3 3
4 4
Reversestack (stack); Post Station becomes
4
3
2
Object TOP2 = stack. Pop ();
3
2
(Note that 1 is the top element of the stack, and 4 is the stack-bottom element)
Then Reversestack (stack);//P1 becomes
2
3
Then stack. Push (top), change to
1
2
3
(This step finds that the stack bottom element 4 is removed)
Here's the
3
2
1
Finally,
4
3
2
1
2, sorting stacks, using the idea of reverse stack to achieve
void Sort (stack& stack) { if (stack. Count = = 0) return; Object top = stack. Pop (); Sort (stack); if (stack. Count = = 0) { stack. Push (top); return; } Object TOP2 = stack. Pop (); if ((int) top > (int) top2) { stack. Push (top); Sort (stack); Stack. Push (TOP2); } else { stack. Push (TOP2); Sort (stack); Stack. Push (top);} }
O (1) Time complexity reverse stack and sort stack