C++使用一個棧實現(xiàn)另一個棧的排序算法示例
更新時間:2017年05月10日 08:53:02 作者:難免有錯_
這篇文章主要介紹了C++使用一個棧實現(xiàn)另一個棧的排序算法,結合實例形式分析了C++借助輔助棧實現(xiàn)棧排序算法的相關操作技巧,需要的朋友可以參考下
本文實例講述了C++用一個棧實現(xiàn)另一個棧的排序算法。分享給大家供大家參考,具體如下:
題目:
一個棧中元素類型為整型,現(xiàn)在想將該棧從頂?shù)降装磸男〉酱蟮捻樞蚺判?,只許申請一個輔助棧。
除此之外,可以申請新的變量,但不能申請額外的數(shù)據(jù)結構。如何完成排序?
算法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++程序設計有所幫助。
相關文章
Java?C++?算法題解leetcode669修剪二叉搜索樹示例
這篇文章主要為大家介紹了Java?C++?算法題解leetcode669修剪二叉搜索樹示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
Linux下C語言的fork()子進程函數(shù)用法及相關問題解析
fork()函數(shù)在Linux下可以用于產(chǎn)生一個子進程,這里我們挑選了兩個fork相關的面試題,來看一下Linux下C語言的fork()子進程函數(shù)用法及相關問題解析2016-06-06
Qt采用線程以隊列方式實現(xiàn)下發(fā)數(shù)據(jù)
在C++中隊列是一種常用的數(shù)據(jù)結構之一,一種特殊的線性表,一般采用先進先出的方式。本文主要為大家介紹了Qt如何以隊列方式實現(xiàn)下發(fā)數(shù)據(jù),感興趣的可以了解一下2022-10-10

