前言:
栈排序,是利用栈的特性进行排序的,这里就是指先进后出这个特性。
例题 :
这里可以允许用到两个栈,也就是多用一个辅助栈。
具体思路:就是循环遍历元素,当发现入栈的元素x要比栈顶要大的时候,则循环将栈顶小于x的元素放到辅助栈中,然后把x入栈,最后把辅助栈的元素重新入栈。
# include <iostream>
# include <algorithm>
# include <cstdlib>
# include <cstdio>
# include <stack>
using namespace std;
stack<int> a,b;
int book[1000];
int main(void)
{
int n;
cin>>n;
srand(unsigned(time(NULL)));
for(int i=1;i<=n;++i){
book[i] = rand()%100+1;
cout<<book[i]<<' ';
}cout<<endl;
for(int i=1;i<=n;++i){
while(!a.empty() && a.top()<book[i]){
b.push(a.top());
a.pop();
}
a.push(book[i]);
while(!b.empty()){
a.push(b.top());
b.pop();
}
}
while(!a.empty()){
cout<<a.top()<<' ';
a.pop();
}
return 0;
}