[Algorithm] Community Stack
Regarding the operations on Stack you can see here
Since Stack is a list of links to form front to back, so we can not direct public 2 Stack. Suppose need community at Stack Stack S2 S1, we use 1 Stack Stemp to store intermediate values of S2 and then only turn putting values into S1 Stemp.
If community 2 Stack sang 1 The new stack is to transfer all 2 Stack Stack to mediate before switching to the necessary public Stack. Stack plus many similar actions.

#include <iostream>
#include <stack>
using namespace std;
int main(){
stack <int> S1;
stack <int> S2;
stack <int> Stemp;
// create 2 Stack
for (int i = 0; i < 5; i++)
S1.push(i); // S1 : 0 1 2 3 4
for (int i = 5; i < 10; i++)
S2.push(i); // S2 : 5 6 7 8 9
// move S2 to Stemp;
while (!S2.empty()){
int x = S2.top();
S2.pop();
Stemp.push(x); // Stemp : 9 8 7 6 5
}
// move Stemp to S1
while(!Stemp.empty()){
int x = Stemp.top();
Stemp.pop();
S1.push(x); // S1 : 0 1 2 3 4 5 6 7 8 9
}
// show S1
while (!S1.empty()){
int x = S1.top();
S1.pop();
cout << x << " ";
}
return 0;
}



Recent Comments