本文實(shí)例講述了C++用一個(gè)棧實(shí)現(xiàn)另一個(gè)棧的排序算法。分享給大家供大家參考,具體如下:
題目:
一個(gè)棧中元素類型為整型,現(xiàn)在想將該棧從頂?shù)降装磸男〉酱蟮捻樞蚺判颍辉S申請(qǐng)一個(gè)輔助棧。
除此之外,可以申請(qǐng)新的變量,但不能申請(qǐng)額外的數(shù)據(jù)結(jié)構(gòu)。如何完成排序?
算法C++代碼:
class Solution{public: //借助一個(gè)臨時(shí)棧排序源棧 static void sortStackByStack(stack<int>& s) { stack<int>* sTemp = new stack<int>; while (!s.empty()) { int cur = s.top(); s.pop(); //當(dāng)源棧中棧頂元素大于臨時(shí)棧棧頂元素時(shí),將臨時(shí)棧中棧頂元素放回源棧 //保證臨時(shí)棧中元素自底向上從大到小 while (!sTemp->empty() && cur > sTemp->top()) { int temp = sTemp->top(); sTemp->pop(); s.push(temp); } sTemp->push(cur); } //將臨時(shí)棧中的元素從棧頂依次放入源棧中 while (!sTemp->empty()) { int x = sTemp->top(); sTemp->pop(); s.push(x); } }};測(cè)試用例程序:
#include <iostream>#include <stack>using namespace std;class Solution{public: //借助一個(gè)臨時(shí)棧排序源棧 static void sortStackByStack(stack<int>& s) { stack<int>* sTemp = new stack<int>; while (!s.empty()) { int cur = s.top(); s.pop(); //當(dāng)源棧中棧頂元素大于臨時(shí)棧棧頂元素時(shí),將臨時(shí)棧中棧頂元素放回源棧 //保證臨時(shí)棧中元素自底向上從大到小 while (!sTemp->empty() && cur > sTemp->top()) { int temp = sTemp->top(); sTemp->pop(); s.push(temp); } sTemp->push(cur); } //將臨時(shí)棧中的元素從棧頂依次放入源棧中 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");}運(yùn)行結(jié)果:
排序前的棧:2 9 4 8 6 7 5排序后的棧:9 8 7 6 5 4 2
希望本文所述對(duì)大家C++程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答