题目要求有些无厘头:一个输入栈存放初始数据,一个相同容量的输出栈,借助一个临时空间完成排序。
#include <iostream>
#include <stack>
using namespace std;
typedef stack<int> s_i;
s_i StackSort(s_i &r){
s_i s;
int t;
int size = r.size();
if (size < 2)
return r;
t = r.top(); //pop()的类型为void
r.pop();
while (s.size()!=size){ //解决问题之道
if (s.empty() || t <= s.top()){ //若有序栈空或者栈中元素小于要进栈的元素时
s.push(t);
if (!r.empty()) //top(),pop()之前检查一下不为过
{
t = r.top();
r.pop();
} //曾经写错在if之前
}
else{
r.push(s.top());
s.pop();
}
}
return s;
}
int main(){
int n;
s_i random;
scanf("%d", &n);
int t;
while (n--){
scanf("%d", &t);
random.push(t);
}
s_i sorted;
sorted= StackSort(random);
while (!sorted.empty()){
printf("%d\n",sorted.top());
sorted.pop();
}
return 0;
}
此题主教大人们给出解决最后一个数据的方法与我的方法不太一样。主教大人们是顺着原来的思路:
while(!r.empty()||/*-------*/){
if(...){...;}
else{...;}
}
/*------*/;
两处配合哪里出了问题就解决哪里,有了新问题再去解决新问题。