国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

隊列和棧面試題(一)— 請編寫一個程序,按升序?qū)_M行排序,要求最多只能使用一個額外的棧存放臨時數(shù)據(jù)

2019-11-14 12:04:12
字體:
供稿:網(wǎng)友

題目:請編寫一個程序,按升序?qū)_M行排序,要求最多只能使用一個額外的棧存放臨時數(shù)據(jù),但不得將元素復(fù)制到別的數(shù)據(jù)結(jié)構(gòu)中。


思路:首先申請一個棧sta來存放數(shù)據(jù)棧,再申請一個輔助棧help來存放臨時數(shù)據(jù),然后比較sta彈出的棧頂?shù)闹祌es與help棧頂元素的大小。

當sta棧不為空時:

1、如果help.empty()或者res<=help.top(),那么就把res的值壓入help棧中;

2、如果help不為空并且res>help.top(),那么就把help中棧頂?shù)闹祻棾霾喝雜ta棧,最后把res的值壓入help棧中。

具體可看如下過程圖:

1 2 3 4 5 6 7 8 9


示例代碼:

#include<iostream>#include<string>#include<stack>//pop,top,push#include<vector>using namespace std;class TwoStacks {public: vector<int> twoStacksSort(vector<int> numbers) { stack<int> sta; for(vector<int>::reverse_iterator riter=numbers.rbegin();riter!=numbers.rend();riter++) sta.push(*riter); StackSort(sta); vector<int> res; while(!sta.empty()) { res.push_back(sta.top()); sta.pop(); } return res; } void StackSort(stack<int> &sta) { stack<int> help; while(!sta.empty()) { int res=sta.top(); sta.pop(); if(help.empty()||res<=help.top()) help.push(res); else { while(!help.empty()&&res>help.top()) { sta.push(help.top()); help.pop(); } help.push(res); } } while(!help.empty()) { sta.push(help.top()); help.pop(); } }};int main(){ int a[5]={1,2,3,4,5}; TwoStacks A; vector<int> arr(a,a+5),res; res=A.twoStacksSort(arr); for(vector<int>::iterator iter=res.begin();iter!=res.end();iter++) cout<<*iter<<" "; return 0;}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 桐庐县| 克什克腾旗| 徐闻县| 寿宁县| 漠河县| 太白县| 阜南县| 黔西县| 安顺市| 林芝县| 苏尼特右旗| 上林县| 安福县| 建瓯市| 青神县| 德令哈市| 清涧县| 中卫市| 沛县| 冀州市| 靖州| 汕头市| 沙坪坝区| 察雅县| 高雄市| 东莞市| 虹口区| 顺昌县| 易门县| 阜平县| 邵东县| 神木县| 华蓥市| 汾西县| 阿尔山市| 贡山| 宣恩县| 新巴尔虎左旗| 南阳市| 保定市| 岳西县|