C++_homework_StackSort
生活随笔
收集整理的这篇文章主要介绍了
C++_homework_StackSort
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
顾名思义(?)类似于单调栈?维护一个单调递减的栈。一旦准备入栈的元素大于栈顶元素,栈一直弹出直到准备入栈的元素小于等于栈顶元素,弹出的元素压入另一个tmp栈中。
#include <iostream>
#include <stack>
#include <cstdlib>
#include <ctime>
using namespace std; void StackSort(stack<int>& s)
{
stack<int> tmp;
while(!s.empty()){
tmp.push(s.top());
s.pop();
}
while(!tmp.empty()){
if(s.empty()){s.push(tmp.top());tmp.pop();}
else{
int x=tmp.top();
tmp.pop();
if(x<=s.top()) s.push(x);
else{
while(!s.empty()&&x>s.top()){
tmp.push(s.top());
s.pop();
}
s.push(x);
}
}
}
} void display(stack<int> s)
{ while (!s.empty()) cout<<s.top()<<endl,s.pop();
cout<<endl;
}
int main(int argc,char**argv)
{ const int n{};
srand((unsigned)time());
stack<int> s;
for (int i{};i<n;i++) s.push(rand()%);
cout<<"Before sorting:"<<endl<<endl; display(s);
cout<<"After sorting:"<<endl; StackSort(s); display(s);
return ;
}
s:
tmp: 8 7 9
s: 9
tmp: 8 7
s: 9 7
tmp: 8
s: 9 8
tmp: 7
s: 9 8 7
tmp:
总结
以上是生活随笔为你收集整理的C++_homework_StackSort的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: mysql中mysql数据库丢失报错Ca
- 下一篇: TOYS POJ 2318 计算几何 叉