Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Created January 24, 2014 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolinwei/8591150 to your computer and use it in GitHub Desktop.
Save tolinwei/8591150 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <stack>
using namespace std;
/*
s:
2
8
9
3
7
11
5
temp:
3
ret:
9
8
2
*/
stack<int> sort_stack(stack<int> s)
{
stack<int> ret;
while (!s.empty()) {
int temp = s.top();
s.pop();
while (!ret.empty() && ret.top() > temp) {
s.push(ret.top());
ret.pop();
}
ret.push(temp);
}
return ret;
}
int main(int argc, char *argv[]) {
stack<int> s;
s.push(5);
s.push(11);
s.push(7);
s.push(3);
s.push(9);
s.push(8);
s.push(2);
stack<int> ret = sort_stack(s);
while (!s.empty()) {
cout << s.top() << endl;
s.pop();
}
cout << endl;
while (!ret.empty()) {
cout << ret.top() << endl;
ret.pop();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment