【问题标题】:Find next greater of every element using stack使用堆栈查找每个元素的下一个较大值
【发布时间】:2018-11-08 15:03:52
【问题描述】:

我正在尝试查找数组的下一个更大元素。我的逻辑是正确的,代码也没有错误,但我无法为每个索引获取输出。我只为索引 0 获取它。之后,它给出了分段错误。这里a 是输入数组,n 是数组a 的大小,next 也是一个数组,用于存储a 的直接更大元素。

   void gofindnextelement(int a[],int next[],int n)
   {
    stack<int>s;
    s.push(0);
    int i,curr;
    for( i=1;i<n;i++){
         curr=a[i];
         while(a[s.top()]<curr && s.empty()==0){
         next[s.top()]=curr;
         cout<<"index=" << s.top()<<"--->"<<next[s.top()]<<endl;
         s.pop();
         } 
         s.push(i);

   }    
   while(s.empty()==0)
     { 

    next[s.top()]=-1;
    cout<<"index=" << s.top()<<"--->"<<next[s.top()]<<endl;
    s.pop();
    }

for(int i=0;i<n;i++)
cout<<next[i]<< " "<<endl;      

 }

【问题讨论】:

  • 但是我现在做了以下更改“while (s.empty()==0&&a[s.top()]

标签: c++ arrays data-structures stack


【解决方案1】:

如果s 为空,则s.top() 会导致未定义行为。所以

s.empty()==0 && a[s.top()]<curr

是安全的,但是

a[s.top()]<curr && s.empty()==0

不是。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 2021-10-30
    • 1970-01-01
    • 2013-05-29
    • 2022-12-31
    • 1970-01-01
    • 2016-11-07
    • 2017-09-12
    相关资源
    最近更新 更多