#include<iostream>
#include<stack>
using namespace std;
/*
通过使用两个栈,来实现插入排序
result 排好序的栈
randomstack 随机生成的乱序的栈
①弹出乱序的栈顶元素,赋值给tmp后并pop()删除
②若result栈为空或者result栈顶元素<=tmp,把tmp压入result栈,更新tmp;
若result栈不为空且result栈顶元素大于tmp,则把大于tmp的元素依次
pop()到randomstack栈,直至result栈为空或者result栈顶元素<=tmp,
把tmp压入result栈,更新tmp
*/
stack<int> insertSorting(stack<int> randomstack) {
stack<int> result;//result为存储,排好序数字的栈
if (randomstack.empty()) {//特殊情况,输入的栈randomstack为空,直接返回
return result;
}
int tem = randomstack.top();//将乱序的栈顶元素传给tem后,并删除
randomstack.pop();
while (!randomstack.empty() ||tem<result.top()) {
if (result.empty() || result.top() <= tem) {//如果result为空或者result栈顶元素<tem
result.push(tem); // 直接压栈
tem = randomstack.top(); //更新tem
randomstack.pop();
}
else
{
randomstack.push(result.top());//将大于tem的元素压入待排序的栈中
result.pop();//并从result栈中删除
}
}
result.push(tem);//while循环结束,说明randomstack为空,且此时tmp大于result栈顶元素;
return result;
}
int main() {
stack<int> s;
s.push(1);
s.push(100);
s.push(30);
s.push(20);
s.push(10);
s.push(111);
s.push(2);
s.push(0);
s.push(60);
s.push(10);
cout << "排序后\n";
stack<int> r;
r = insertSorting(s);
while (!r.empty()) {
cout << r.top();
cout << '\n';
r.pop();
}
system("PAUSE");
return 1;
}
在这里插入代码片