函数,该函数将在堆栈底部保留最小的出现次数

Function that will leave the smallest occurrences at the bottom of stack

本文关键字:函数 保留 堆栈 栈底部      更新时间:2023-10-16

我正在尝试编写一个堆栈,以便最小元素的所有出现都在堆栈的底部,而其他元素的顺序保持不变。例如,如果我有堆栈[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中元素的顺序与mincount的顺序相反。现在,我们将把count个值为min的元素推回到s中。然后开始从ts的弹出和推送,除了等于min的元素。