使用堆栈查找下一个更大的元素

时间:2018-05-29 21:22:59

标签: c++ arrays data-structures stack

我试图找到下一个更大的数组元素。我的逻辑是正确的,代码没有错误,但我无法获得每个索引的输出。我只是为索引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;      

 }

1 个答案:

答案 0 :(得分:1)

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

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

是安全的,但是

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

不是。