Sort Stack
template <typename T>
stack<T> sortStack(stack<T> s1) {
if (s1.size() <= 1) return s1;
// start us off
stack<T> temp;
int pop_count = 0;
temp.push(s1.top());
s1.pop();
while (!s1.empty()) {
// grab top element of s1
T temp2 = s1.top();
s1.pop();
// find correct position in temp
while (!temp.empty() && temp.top() < temp2) {
s1.push(temp.top());
temp.pop();
pop_count++;
}
temp.push(temp2);
// place back
for (int i = 0; i < pop_count; i++) {
temp.push(s1.top());
s1.pop();
}
pop_count = 0;
}
return temp;
}
int main() {
vector<int> v = { 1,5,2,10,3,3,3,3,3,100,1001,232 };
stack<int> s;
for (auto i : v) {
s.push(i);
}
stack<int> s2 = sortStack(s);
while (!s2.empty()) {
cout << s2.top() << " ";
s2.pop();
}
pause();
}Last updated