C++_homework_StackSort
2024-08-21 02:58:35
顾名思义(?)类似于单调栈?维护一个单调递减的栈。一旦准备入栈的元素大于栈顶元素,栈一直弹出直到准备入栈的元素小于等于栈顶元素,弹出的元素压入另一个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:
最新文章
- Poj The xor-longest Path 经典题 Trie求n个数中任意两个异或最大值
- 实用控件分享:自定义逼真相机光圈View
- [FPGA] 2、新建并运行一个工程
- SQLServer中的死锁的介绍
- 在页面头部<;!DOCTYPE html ....>; 前面不能有任何输出
- js onclick=";return test()";事件返回值,对有些事件,会影响默认动作的执行。如:onclick和onsubmit
- 【KMP+DP】Count the string
- 事件绑定之.bind()
- 质因数分解的rho以及miller-rabin
- SpringMVC(五):@RequestMapping下使用@RequestParam绑定请求参数值
- 快速沃尔什变换(FWT)及K进制异或卷积&;快速子集变换(FST)讲解
- yii2 gridview默认排序
- Spring-Boot配置文件web性能(服务器)配置项
- 关闭linux服务器防火墙
- 关于Bootstrap的入门知识
- jquery原理的简单分析,让你扒开jquery的小外套。
- [leetcode]Convert Sorted List to Binary Search Tree @ Python
- Xamarin.Android RelativeLayout
- 使用抓包工具pproxy
- hdu 1114 dp动规 Piggy-Bank