函数,该函数将在堆栈底部保留最小的出现次数
Function that will leave the smallest occurrences at the bottom of stack
我正在尝试编写一个堆栈,以便最小元素的所有出现都在堆栈的底部,而其他元素的顺序保持不变。例如,如果我有堆栈[4,3,1,5,8,1,4],它将变为[4,3,5,8,4,1,1],但我的问题是顺序发生了变化所以我会得到这样的东西[4,5,3,4,8,1,1]
#include <iostream>
#include <stack>
using namespace std;
void minstack(stack<int> &s)
{
stack<int> t1,t2;
int count=0,min;
if(!s.empty())
{
while(!s.empty())
{
if(s.top() <min)
{ min=s.top();
count=0;
}
t1.push(s.top()); s.pop();
count++;
}
for(int i = 0 ; i<count;i++)
{
s.push(min);
}
while(!t1.empty())
{
if(t1.top()!=min);
{ s.push(t1.top());
}
t1.pop();
}
}
}
int main()
{
stack <int> s;
s.push(4);
s.push(3);
s.push(1);
s.push(5);
s.push(8);
s.push(1);
s.push(4);
minstack(s);
while(!s.empty())
{
cout<<s.top()<<" "; s.pop();
}
}
这里有一个想法。首先,我们需要找到堆栈中最小的元素。定义临时堆栈t
。现在,我们将从s
中逐个弹出所有元素,并将它们推送到t
中。同时,跟踪最小值min
以及到目前为止在count
中的弹出过程中遇到的次数。完成此操作后,请注意t
中元素的顺序与min
和count
的顺序相反。现在,我们将把count
个值为min
的元素推回到s
中。然后开始从t
到s
的弹出和推送,除了等于min
的元素。
相关文章:
- 保留对其他类的成员函数的引用
- 局部变量保留函数中的值
- 保留函数指针模板参数
- C++矢量复制构造函数和赋值运算符是否也复制保留空间?
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 将成员函数保留为未定义
- C++:如何为多个重载函数保留通用代码路径?
- 我应该保留这个函数来查找第 n 个素数还是可以优化?
- 函数,该函数将在堆栈底部保留最小的出现次数
- 如何在共享库中保留静态库中的自由函数
- 保留的函数名称可以重载吗?
- OMNET++ 如何保留 AODVRouting 类中的所有函数,但仅覆盖发送 AODVPacket 函数?
- 如果引用应该保留,不删除析构函数中的指针会导致内存泄漏吗?
- 我的单例中的数组在离开函数后没有保留信息,然后在尝试再次访问信息时崩溃
- openCV Mat 中的值在自定义类构造函数中设置后不会保留
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 内联函数是否在内联函数中保留其上下文
- 如何在内联程序集中调用函数时保留堆栈
- 如何为同一类对象的成员函数保留单独的变量副本?
- 即使阵列腐烂到指针,如何将函数的参数保留为数组,这很好