博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[CareerCup] 3.6 Sort Stack 栈排序
阅读量:4476 次
发布时间:2019-06-08

本文共 921 字,大约阅读时间需要 3 分钟。

 

3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty.

 

这道题让我们对栈进行排序,栈顶放大的元素,而且限定了我们只能用一个辅助栈。那么我们的思路是,先取出给定栈的栈顶元素存入到一个临时变量中,然后我们看辅助栈的栈顶元素是否大于取出的元素,大的话就把辅助栈的栈顶元素压入给定栈中,直到辅助栈为空或是栈顶元素小于取出值,这时将取出值压入辅助栈,然后继续从给定栈中取值,以此类推直至给定栈取空,这时候辅助栈就是排序完成的结果,返回即可,参见代码如下:

 

class Solution {public:    stack
sort(stack
s) { stack
res; while (!s.empty()) { int v = s.top(); s.pop(); while (!res.empty() && res.top() > v) { s.push(res.top()); res.pop(); } res.push(v); } return res; }};

 

转载于:https://www.cnblogs.com/grandyang/p/4679143.html

你可能感兴趣的文章
alibaba.fastjson.JSONObject 解析
查看>>
终于有人把Elasticsearch原理讲透了
查看>>
Java使用POI 读取和写入Excel指南
查看>>
shell脚本中各类括号的作用(小结)
查看>>
借用Snippet插件美化博客中的代码
查看>>
深入研究java.lang.Runtime类
查看>>
10677 我们仍未知道那天所看见的花的名字
查看>>
ScanTailor-ScanTailor 自动矫正图像歪斜
查看>>
UVA GCD - Extreme (II)
查看>>
完成个人中心—导航标签
查看>>
【C++】C++中变量的声明与定义的区别
查看>>
前端性能优化
查看>>
static
查看>>
属性动画
查看>>
Swift 字符串
查看>>
Python 生成器 Generator 和迭代器 Iterator
查看>>
实现icon和文字垂直居中的两种方法-(vertical-align and line-height)
查看>>
[CareerCup] 3.6 Sort Stack 栈排序
查看>>
Beta版总结会议
查看>>
Cocos2d-x中使用的数据容器类
查看>>