Q:Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.
A: 再利用另外一个栈来模拟插入排序。 sin是原来的栈,sout是用来储存排序后的栈,
将sin.top() 元素保存在一个临时变量tmp里面,同sout中的元素比较,如果大于sout的top元素,那么就压入当前位置,否则将sout的top元素压入sin之中,tmp继续与sout的top比较,直到sout为空。
#include <iostream>
#include <stack>
using namespace std;
stack<int> sortStack(stack<int> s) {
stack<int> t;
if (s.empty()) {
return t;
}
t.push(s.top());
s.pop();
while (!s.empty()) {
int tmp = s.top();
s.pop();
while (!t.empty() && t.top() > tmp) {
s.push(t.top());
t.pop();
}
t.push(tmp);
}
return t;
}
int main() {
int a[5] = {3,5,2,4,1};
stack<int> s;
for (int i = 0; i < 5; i++) {
s.push(a[i]);
}
while (!s.empty()) {
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
for (int i = 0; i < 5; i++) {
s.push(a[i]);
}
s = sortStack(s);
while (!s.empty()) {
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
return 0;
}