-3
这里有约束:函数修改堆栈时如何将堆栈传递给函数?
- 只有STL必须用于堆栈创建(不使用结构来创建堆栈)
- 排序堆不使用
我想通了任何循环该解决方案约束2.但是,当我使用STL创建堆栈以满足约束1时,堆栈未被排序并且输出与输入相同。
预期输出:5 4 3 2 1 我的输出:1 2 4 3 5
下面是代码:
#include<iostream>
#include<stack>
using namespace std;
void SortedInsert(stack<int> S,int x)
{
if(S.empty() || x > S.top())
S.push(x);
else
{
int temp = S.top();
S.pop();
SortedInsert(S,x);
S.push(temp);
}
}
void StackSort(stack<int> S)
{
if(!S.empty())
{
int x = S.top();
S.pop();
StackSort(S);
SortedInsert(S,x);
}
}
void main()
{
int arr[5] = {1,2,4,3,5};
stack<int> S;
for(int i=4 ; i>=0 ; i--)
S.push(arr[i]);
StackSort(S);
while(!S.empty())
{
cout<<S.top()<<" ";
S.pop();
}
cin.get();
}