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
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有