Q3.6 sort a stack in ascending order
来源:互联网 发布:分布式数据库架构师 编辑:程序博客网 时间:2024/04/28 00:52
Q:Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.
A: 再利用另外一个栈来模拟插入排序。 sin是原来的栈,sout是用来储存排序后的栈,
将sin.top() 元素保存在一个临时变量tmp里面,同sout中的元素比较,如果大于sout的top元素,那么就压入当前位置,否则将sout的top元素压入sin之中,tmp继续与sout的top比较,直到sout为空。
#include <iostream>#include <stack> using namespace std;stack<int> sortStack(stack<int> s) {stack<int> t;if (s.empty()) {return t;}t.push(s.top());s.pop();while (!s.empty()) {int tmp = s.top();s.pop();while (!t.empty() && t.top() > tmp) {s.push(t.top());t.pop();}t.push(tmp);}return t;}int main() {int a[5] = {3,5,2,4,1};stack<int> s;for (int i = 0; i < 5; i++) {s.push(a[i]);}while (!s.empty()) {cout<<s.top()<<" ";s.pop();}cout<<endl;for (int i = 0; i < 5; i++) {s.push(a[i]);}s = sortStack(s);while (!s.empty()) {cout<<s.top()<<" ";s.pop();}cout<<endl;return 0;}
0 0
- Q3.6 sort a stack in ascending order
- 【18】Sort a stack in ascending order
- Ch3-6: sorting a stack in an ascending order
- Thursday, August 16, 2012How to sort ArrayList in java - List Sorting - Ascending Descending Order
- Sort Stack in increasing/decreasing Order.
- indices should be one-based and in ascending order
- CCI: Sort a stack
- stack type, full-ascending, full-descending, empty-ascending, empty-descending
- How to sort an array in Ruby to a particular order?
- Q3.2 Stack with Min
- process a container in a reverse order
- Sort stack
- Order a column conditional in SQL
- Print A Tree In Vertical Order
- Output a string in reverse order
- return the minimum value in a stack
- [CF 81A]Plug-in[stack]
- Stack_Queue 把栈排序 Sort a stack @CareerCup
- 【Python】学习笔记
- HDU 1316 -- How Many Fibs?(Java)
- linux性能分析及调优
- 在屏幕上显示0—360的cos(x)曲线与直线f(x)=45*(y-1)+31的迭加图形。
- 汉诺塔II
- Q3.6 sort a stack in ascending order
- 解决eclipse出现This Android SDK requires Andro...date ADT to the latest version.问题
- 《敏捷软件开发》读书笔记(四)
- vs中丢失帮助查看器(HelpViewer)如何处理
- 图解数据结构之算法
- TortoiseSVN中Branching和Merging实践
- 邢帅——一个逆袭的草根
- 多柱汉诺塔最优算法设计探究
- Eclipse中clear工程以后,R文件消失及解决办法