本文實例講述了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
希望本文所述對大家C++程序設計有所幫助。
新聞熱點
疑難解答
圖片精選