用一个栈来实现另一个栈的排序
来源:互联网 发布:网络语rbq是什么意思 编辑:程序博客网 时间:2024/04/26 14:19
题目:一个栈中元素的类型为整数,现在将该栈从顶到底按从大到小的顺序排序,只许申请一个栈,除此之外可以申请新的变量,但不能申请额外的数据结构。
算法思路:
将要排序的栈记为sta,申请辅助栈为st_help.保存sta栈顶元素到cur变量,并pop栈顶元素。
1)如果cur小于等于st_help栈顶元素,则将cur压入st_help
2) 如果cur小于st_help 栈顶元素,则将st_help栈顶元素压入sta,并pop st_help栈顶元素,直到cur小于等于st_help栈顶元素,然后压入cur到st_help.
3)重复 1),2),直到将所有的sta为空,然后将st_help中的元素全部压如sta.
#include <iostream>#include <stack>#include <string>using namespace std;void SortStackByStack(stack<int> & sta){ stack<int> st_help; int cur; while(!sta.empty()) { cur = sta.top(); sta.pop(); if(st_help.empty() || cur <= st_help.top()) st_help.push(cur); else { while(!st_help.empty() && (st_help.top() < cur)) { int temp = st_help.top(); st_help.pop(); sta.push(temp); } st_help.push(cur); } }//first while while(!st_help.empty()) { cur = st_help.top(); st_help.pop(); sta.push(cur); }}int main(void){ stack<int> st; int val; while(cin>>val) { st.push(val); } SortStackByStack(st); while(!st.empty()) { cout <<st.top()<<" "<<endl; st.pop(); } return 0;}
0 0
- 【栈】用一个栈来实现另一个栈的排序
- 用一个栈来实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 数据结构5 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 1_5用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- C++ 使用一个栈实现另一个栈的排序
- 栈和队列之用一个栈实现另一个栈的排序
- 栈和队列(5)——用一个栈实现对另一个栈的排序
- 1栈和队列--用一个栈实现另一个栈的排序
- 栈和队列——用一个栈实现另一个栈的排序
- 栈和队列 用一个栈实现另一个栈的排序
- 栈和队列---用一个栈实现另一个栈的排序
- php生成XML文件
- Service生命周期调用
- 网络获取图片加入导航页
- java对象和xml之间转换--Jaxb--1
- Codeforces Round #377 (Div. 2)(A+B)
- 用一个栈来实现另一个栈的排序
- axure如何快速上手
- php生成XML文件
- 分享一个简单实用的前台计时器
- Java泛型学习笔记
- 2017年链家校招前端面试题
- linux常用命令总结(个人摘录)ftp ssh配置 linux打包命令等
- HDU 5723 - Abandoned country
- react 学习笔记之AJAX数据请求和使用