我试图找到下一个更大的数组元素。我的逻辑是正确的,代码没有错误,但我无法获得每个索引的输出。我只是为索引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;
}
答案 0 :(得分:1)
如果s
为空,则s.top()
会导致未定义的行为。所以
s.empty()==0 && a[s.top()]<curr
是安全的,但是
a[s.top()]<curr && s.empty()==0
不是。