004使用一个栈对另一个栈完成排序(C++实现)

来源:互联网 发布:三毛梦里花落知多少txt 编辑:程序博客网 时间:2024/04/30 10:07
#include<iostream>
#include<stack>
using namespace std;
//这个题目很有意思,就是我比你大,你就给我出来,我进去,然后你们在入栈
void display(stack<int> a)//这里将传地址还是传值,表现的很好
{
for (int i = 0; i < 9; i++)
{
cout << a.top() << " ";
a.pop();
}
cout << endl;
}
void sort(stack<int>& a)
{

stack<int>help;
while (!a.empty())
{
int cur = a.top();
a.pop();
while (!help.empty()&&cur > help.top())
{
a.push(help.top());
help.pop();
}
help.push(cur);
}
display(help);
while (!help.empty())
{
int val = help.top();
a.push(val);
help.pop();
}
}
void main()
{
stack<int>a;
a.push(11);
a.push(77);
a.push(22);
a.push(33);
a.push(77);
a.push(44);
a.push(11);
a.push(6);
a.push(8);


display(a);
sort(a);
display(a);
system("pause");
}



思路来源:程序员代码面试指南 -左程云


1 0