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的更多相关文章
随机推荐
- java攻城狮之路--复习xml&dom_pull编程
xml&dom_pull编程: 1.去掉欢迎弹窗界面:在window项的preferences选项中输入“configuration center” 找到这一项然后 把复选框勾去即可. ...
- lnmp环境搭建后续-php安装
安装PHP7: 下载# wget http://PHP.net/get/php-7.0.2.tar.gz/from/a/mirror 建议安装之前先看看安装帮助文件INSTALL 解压安装 # tar ...
- Flask 框架构建
Flask 框架构建,目标构建成Django类似的结构 一. 先看看构建后的效果 # 第一次初始化 python manage.py db init # 生成数据库版本 python manage.p ...
- codeforces_731D_(前缀和)(树状数组)
D. 80-th Level Archeology time limit per test 2 seconds memory limit per test 256 megabytes input st ...
- linux安装mysql可视化工具MySQL-workbench 连接数据库 执行sql
Step1:建立数据库连接 点击新建连接的按钮,符号是“+”的按钮,出现下图,在“Connection name”输入连接名称. 填写连接信息 输入数据库连接密码 测试连接: 再次点击连接时会要求输入 ...
- 最小生成树算法Kruskal详解
要讲Kruskal,我们先来看下面一组样例. 4 5 1 2 3 1 4 5 2 4 7 2 3 6 3 4 8 14 画出来更直观一些,就是上面的这张图. 智商只要不是0的(了解最小生成树是什么的童 ...
- C++实现双人枪战游戏
//单机版枪战游戏,喜欢就拿走,把赞留下//by floatiy #include<iostream> #include<cstdio> #include<windows ...
- array_map 等php回调函数使用问题(关联数组下标获取)
前言:我自己用此类回调函数,来替代 foreach 纯粹是用为代码的简洁性,让代码更好看.(我有点代码小洁癖~) 1.array_reduce 当迭代处理一个一维索引数组时,在回调函数内是无法获取到当 ...
- PAT 1060. Are They Equal
If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered ...
- qwb和李主席
qwb和李主席 Time Limit: 4 Sec Memory Limit: 128 MB Description qwb和李主席打算平分一堆宝藏,他们想确保分配公平,可惜他们都太懒了,你能帮助他 ...