首页 > 解决方案 > 将最小出现次数留在堆栈底部的函数

问题描述

我正在尝试编写一个堆栈,以便所有出现的最小元素都位于堆栈的底部,而其他元素的顺序保持不变。例如,如果我有堆栈 [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();
}

}

标签: c++stack

解决方案


这是一个想法。首先,我们需要找到堆栈的最小元素。定义一个临时堆栈t。我们现在将一个一个地弹出所有元素s并将它们推入t. 同时,min在弹出过程中跟踪最小值和迄今为止遇到的次数count。完成此操作后,请注意您将在t和 具有min和中具有相反的元素顺序count。现在我们将countvalue 元素的数量推mins. 然后开始弹出并从到推t送到s除了等于的元素min


推荐阅读