C++使用一個棧實現另一個棧的排序算法示例。本站提示廣大學習愛好者:(C++使用一個棧實現另一個棧的排序算法示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++使用一個棧實現另一個棧的排序算法示例正文
作者:難免有錯_
這篇文章主要介紹了C++使用一個棧實現另一個棧的排序算法,結合實例形式分析了C++借助輔助棧實現棧排序算法的相關操作技巧,需要的朋友可以參考下本文實例講述了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++程序設計有所幫助。