对于一个stack,在不借助其他工具类,仅使用pop(),top(),push(),empty()方法。
stack<int> sort(stack<int> p)
{
stack<int> p1,p2;
int x;
x=p.top();
p.pop();
if(p.empty())
{
p.push(x);
return p;
}
while(!p.empty())
{
if(x>p.top())
{
p1.push(p.top());
p.pop();
}
else
{
p2.push(p.top());
p.pop();
}
}
if(!p1.empty())
p1=sort(p1);
if(!p2.empty())
p2=sort(p2);
while(!p1.empty())
{
p.push(p1.top());
p1.pop();
}
p.push(x);
while(!p2.empty())
{
p.push(p2.top());
p2.pop();
}
while(!p.empty())
{
p1.push(p.top());
p.pop();
}
p=p1;
return p;
}