題目:請編寫一個程序,按升序對棧進行排序,要求最多只能使用一個額外的棧存放臨時數據,但不得將元素復制到別的數據結構中。
思路:首先申請一個棧sta來存放數據棧,再申請一個輔助棧help來存放臨時數據,然后比較sta彈出的棧頂的值res與help棧頂元素的大小。
當sta棧不為空時:
1、如果help.empty()或者res<=help.top(),那么就把res的值壓入help棧中;
2、如果help不為空并且res>help.top(),那么就把help中棧頂的值彈出并壓入sta棧,最后把res的值壓入help棧中。
具體可看如下過程圖:
示例代碼:
#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;}新聞熱點
疑難解答