//★题目:用一个栈实现另一个栈的排序
//要求:一个栈中的元素类型为整型,实现该栈从顶到底从大到小的顺序排序,只允许申请一个额外的栈和若干变量
//分析:如果cur小于或等于help的栈顶元素,则将cur直接压入help
// 如果cur大于help的栈顶元素,则将helo的元素逐一弹出,逐一压入stack
// 直到cur小于或等于help的栈顶元素,再将cur压入help
// 对数器采用的方法为:将栈中的元素取出存入数组,采用系统排序函数
// 对数组进行排序,排好序的数组再逐一压入栈中
#include <stack>
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
int srandNum1 = 0;
int srandNum2 = 100;
bool forTest = false;
void sortStackByStack(stack<int> &stk);
stack<int> generateRandomStack(int maxSize, int maxValue, int &size);
void printStack(stack<int> stk);
stack<int> copyStack(stack<int> stk);
void comarator(stack<int> &stk);
bool isEqual(stack<int> stk1, stack<int> stk2);
void printArray(int arr[], int size);
int main()
{
if (!forTest)
{
int size = 0;
int testTime = 50000;
int maxSize = 10;
int maxValue = 10;
bool succeed = true;
for (int i = 0; i < testTime; i++)
{
stack<int> stk1 = generateRandomStack(maxSize, maxValue, size);
stack<int> stk2 = copyStack(stk1);
sortStackByStack(stk1);
comarator(stk2);
if (!isEqual(stk1, stk2))
{
succeed = false;
printStack(stk1);
printStack(stk2);
break;
}
}
if (succeed)
{
cout << "Nice!" << endl;
}
else
{
cout << "Fucking Fucked" << endl;
}
}
else
{
stack<int> stk;
stk.push(5);
stk.push(4);
stk.push(8);
comarator(stk);
printStack(stk);
}
system("pause");
return 0;
}
void sortStackByStack(stack<int> &stk)
{
stack<int> help;
int current;
while (!stk.empty())
{
current = stk.top();
stk.pop();
while (!help.empty() && help.top()<current)
{
stk.push(help.top());
help.pop();
}
help.push(current);
}
while (!help.empty())
{
stk.push(help.top());
help.pop();
}
}
stack<int> generateRandomStack(int maxSize, int maxValue, int &size)
{
srandNum1 += 3;
srandNum2++;
srand((unsigned)time(NULL)*srandNum1*srandNum1*srandNum2*srandNum2*srandNum2);
size = (int)(rand() % (maxSize)+1);
stack<int> stk;
for (int i = 0; i < size; i++)
{
stk.push(rand() % maxValue);
}
//printStack();
return stk;
}
void printStack(stack<int> stk)
{
cout << "top->bottom : ";
stack<int> tmp = stk;
while (!tmp.empty())
{
cout << tmp.top() << " ";
tmp.pop();
}
cout << endl;
}
stack<int> copyStack(stack<int> stk)
{
stack<int> newStack = stk;
return newStack;
}
void comarator(stack<int> &stk)
{
int numSize = stk.size();
int *arr = new int[numSize];
int *arrDst = new int[numSize];
for (int i = 0; i < numSize; i++)
{
arr[i] = stk.top();
stk.pop();
}
sort(arr, arr + numSize);
for (int i = 0; i < numSize; i++)
{
stk.push(arr[i]);
}
}
bool isEqual(stack<int> stk1, stack<int> stk2)
{
if (stk1.size()!=stk2.size())
{
return false;
}
else if (stk1.size()==0)
{
return true;
}
while (!stk1.empty())
{
if (stk1.top()!=stk2.top())
{
return false;
}
stk1.pop();
stk2.pop();
}
return true;
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
栈与队列:用一个栈实现另一个栈的排序(C++带对数器版)
最新推荐文章于 2020-04-10 20:06:10 发布