【发布时间】: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