久久96国产精品久久久-久久发布国产伦子伦精品-久久精品国产精品青草-久久天天躁夜夜躁狠狠85麻豆

技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機(jī)純凈版,64位旗艦版,綠色軟件,免費(fèi)軟件下載基地!

當(dāng)前位置:主頁(yè) > 教程 > 服務(wù)器類 >

C++使用一個(gè)棧實(shí)現(xiàn)另一個(gè)棧的排序算法示例教程

來(lái)源:技術(shù)員聯(lián)盟┆發(fā)布時(shí)間:2017-06-12 12:31┆點(diǎn)擊:

一個(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