题目概述
解题思路
两种思路:其一是每次比较一下当前栈中top元素和下一个元素的大小,然后把小的/大的放到另一个栈中;这样清空一遍以后,相当于把一个数组的相邻元素大小都比较了一遍;然后我们反过来再进行类似的操作,把大的/小的放到另一个栈中,如此反复,直至某次操作以后,不再需要我们颠倒top和下一个元素的顺序,表明排序结束。
另一种做法是:将排序的栈记为A,辅助的栈记为B,在A上pop元素,记得到的元素为a。如果a不大于B的栈顶元素/B为空,则将a放入B;如果a大于B的栈顶元素,则将B中元素依次放入A,直到a不大于B中栈顶元素,再将a放入B。
这两种算法的时间复杂度应该都是O(n^2)。不过我更喜欢第二种思路,它更符合题目的要求。
方法性能
样例代码
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#include<queue>
#include<iomanip>
using namespace std;
int main()
{
int list_num, val_num, temp, temp_top;
bool signal = false;
stack <int> ori_list, sort_list;
cin >> list_num;
for (int vi = 0; vi < list_num; ++vi)
{
cin >> val_num;
ori_list.push(val_num);
}
do
{
if (signal == false)
signal = true;
else
break;
temp = ori_list.top();
ori_list.pop();
while (!ori_list.empty())
{
temp_top = ori_list.top();
ori_list.pop();
if (temp_top > temp)
{
sort_list.push(temp_top);
signal &= false;
}
else
{
sort_list.push(temp);
temp = temp_top;
}
}
sort_list.push(temp);
if (signal == false)
signal = true;
else
break;
temp = sort_list.top();
sort_list.pop();
while (!sort_list.empty())
{
temp_top = sort_list.top();
sort_list.pop();
if (temp_top < temp)
{
ori_list.push(temp_top);
signal &= false;
}
else
{
ori_list.push(temp);
temp = temp_top;
}
}
ori_list.push(temp);
} while (signal == false);
while (!ori_list.empty())
{
temp = ori_list.top();
ori_list.pop();
sort_list.push(temp);
}
while (!sort_list.empty())
{
temp = sort_list.top();
sort_list.pop();
ori_list.push(temp);
}
while (!ori_list.empty())
{
temp = ori_list.top();
cout << temp << ' ';
ori_list.pop();
}
while (!sort_list.empty())
{
temp = sort_list.top();
cout << temp << ' ';
sort_list.pop();
}
return 0;
}