class TwoStacks {//要求只能申请一个辅助栈,不能使用额外的数据结构
public:
vector<int> twoStacksSort(vector<int> numbers) {//numbers为栈中元素序列,栈顶元素为numbers[0]
stack<int> s,help;
for (int i=(int)numbers.size()-1; i>=0; --i) {
s.push(numbers[i]);
}
while (!s.empty()) {
int x = s.top();
s.pop();
while (!help.empty()) {
if(help.top()<x)
{
s.push(help.top());
help.pop();
}
else {
break;
}
}
help.push(x);
}
while (!help.empty()) {
s.push(help.top());
help.pop();
}
numbers.clear();
while (!s.empty()) {
numbers.push_back(s.top());
s.pop();
}
return numbers;
}
};
栈的排序,栈顶元素最大.
最新推荐文章于 2023-05-17 09:00:00 发布