Question: There are two identical stacks A and B. Stack a Stores numbers from large to small: 1, 2, 3, 4, 5, and the stack top is the minimum number 1, stack B is empty. Instead of using other data structures, we need to reverse the numbers in stack a so that the number of top Stacks is up to 5.
Solution:
- This question has a very intuitive idea. First, stack a contains 5 numbers such as 1, 2, 3, 4, and 5, and the top element of the stack is 1. We need to reverse the number to 5, 4, 3, 2, and 1.
- First, we need to extract the minimum value of 1 at the top of the stack and store it in the Temporary Variable temp. Then, we need to transfer the remaining four numbers, 2, 3, and 5 to stack B, insert 1 in the temporary variable to stack a, and finally transfer the number in stack B back to stack a. At this time, a book in stack a is sorted, it is the 1 at the bottom of the stack.
- Repeat the above ideas. This time, we will take out the minimum value 2 at the top of the stack and store it in the temporary variable. We will transfer the remaining 3, 4, and 5 to stack B, and then insert 2 into stack.
Code instance
View code
# Include <iostream> # include <stdlib. h ># include <stack> using namespace STD; Template <typename T> void reverseorder (stack <t> & S1, stack <t> & S2) {s1.push (5 ); s1.push (4); s1.push (3); s1.push (2); s1.push (1); int sortnum = 0; int oristacksize = s1.size (); While (sortnum <oristacksize) {int temp = s1.top (); s1.pop (); While (s1.size ()-sortnum> 0) {s2.push (s1.top (); s1.pop ();} // store the first element into S1 s1.push (temp); ++ sortnum; whil E (! S2.empty () {s1.push (s2.top (); s2.pop () ;}} cout <"reverse stack output:" <Endl; while (! S1.empty () {cout <s1.top () <Endl; s1.pop () ;}} void main () {stack <int> S1; stack <int> S2; reverseorder (S1, S2); System ("pause ");}