用一个栈实现另一个栈的排序
来源:互联网 发布:sql bulk insert 语法 编辑:程序博客网 时间:2024/03/29 02:09
用一个栈实现另一个栈的排序 – C++
题目:
一个栈中元素类型为整型,现在想将该栈从顶到底按从小到大的顺序排序,只许申请一个辅助栈。
除此之外,可以申请新的变量,但不能申请额外的数据结构。如何完成排序?
算法C++代码:
class Solution{public: //借助一个临时栈排序源栈 static void sortStackByStack(stack<int>& s) { stack<int>* sTemp = new stack<int>; while (!s.empty()) { int cur = s.top(); s.pop(); //当源栈中栈顶元素大于临时栈栈顶元素时,将临时栈中栈顶元素放回源栈 //保证临时栈中元素自底向上从大到小 while (!sTemp->empty() && cur > sTemp->top()) { int temp = sTemp->top(); sTemp->pop(); s.push(temp); } sTemp->push(cur); } //将临时栈中的元素从栈顶依次放入源栈中 while (!sTemp->empty()) { int x = sTemp->top(); sTemp->pop(); s.push(x); } }};
测试用例程序:
#include <iostream>#include <stack>using namespace std;class Solution{public: //借助一个临时栈排序源栈 static void sortStackByStack(stack<int>& s) { stack<int>* sTemp = new stack<int>; while (!s.empty()) { int cur = s.top(); s.pop(); //当源栈中栈顶元素大于临时栈栈顶元素时,将临时栈中栈顶元素放回源栈 //保证临时栈中元素自底向上从大到小 while (!sTemp->empty() && cur > sTemp->top()) { int temp = sTemp->top(); sTemp->pop(); s.push(temp); } sTemp->push(cur); } //将临时栈中的元素从栈顶依次放入源栈中 while (!sTemp->empty()) { int x = sTemp->top(); sTemp->pop(); s.push(x); } }};void printStack(stack<int> s){ while (!s.empty()) { cout << s.top() << " "; s.pop(); } cout << endl;}int main(){ stack<int>* s = new stack<int>; s->push(5); s->push(7); s->push(6); s->push(8); s->push(4); s->push(9); s->push(2); cout << "排序前的栈:" << endl; printStack(*s); Solution::sortStackByStack(*s); cout << "排序后的栈:" << endl; printStack(*s); system("pasue");}
运行结果:
排序前的栈:2 9 4 8 6 7 5排序后的栈:9 8 7 6 5 4 2
0 0
- 【栈】用一个栈来实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 数据结构5 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈来实现另一个栈的排序
- 1_5用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- 用一个栈实现另一个栈的排序
- C++ 使用一个栈实现另一个栈的排序
- 栈和队列之用一个栈实现另一个栈的排序
- 栈和队列(5)——用一个栈实现对另一个栈的排序
- 1栈和队列--用一个栈实现另一个栈的排序
- 栈和队列——用一个栈实现另一个栈的排序
- 栈和队列 用一个栈实现另一个栈的排序
- 栈和队列---用一个栈实现另一个栈的排序
- JAVA设计模式(16):行为型-策略模式(Strategy)
- Android学习笔记二十七:连接Wifi
- 计算两个非负整数的最大公约数
- 电脑无法自动获取ip
- Google IO 2016 首日热点
- 用一个栈实现另一个栈的排序
- 打开SDKManager提示failed to execute tools\android.bat
- 实现线程同步的几种方式
- 2016年北京中国云计算技术大会会后感
- Edittext光标始终在最后面
- Execution failed for task ':xxxx:lint'. > Lint found errors in the project; aborting build.
- Android ORM 框架之 greenDAO 使用
- 关于plsql,一定要安装oracle客户端吗?
- NodeMCU介绍