请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。
给定一个int[] numbers(C++中为vector),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。
测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]
class TwoStacks {
public:
vector<int> twoStacksSort(vector<int> numbers) {
// write code here
stack<int> numstack;
stack<int> helpstack;
int n=numbers.size();
for(int i=n-1;i>=0;i--)
numstack.push(numbers[i]);
while(!numstack.empty())
{
int k=numstack.top();
numstack.pop();
while(!helpstack.empty()&&helpstack.top()>k)
{
int m=helpstack.top();
helpstack.pop();
numstack.push(m);
}
helpstack.push(k);
}
numbers.clear();
for(int i=0;i<n;i++)
{
int n=helpstack.top();
helpstack.pop();
numbers.push_back(n);
}
return numbers;
}
};