【问题标题】:I'm getting segmentation fault in this code using stack我使用堆栈在此代码中遇到分段错误
【发布时间】:2020-06-26 13:30:43
【问题描述】:

此代码用于在不使用任何其他数据结构的情况下删除堆栈中的中间元素。我遇到分段错误。帮助我纠正我的代码中的错误。

void deleteMid(stack<char>&st,int n,int temp=0)
{
    
    char x=st.top();
    st.pop();
    deleteMid(st,n,temp+1);
    
    if(temp!=n/2)
    st.push(x);
    
}
int main()
{
   stack<char> st; 
 
    st.push('1'); 
    st.push('2'); 
    st.push('3'); 
    st.push('4'); 
    st.push('5'); 
    st.push('6'); 
    st.push('7'); 
  
    deleteMid(st, st.size()); 
  
    return 0; 
}

【问题讨论】:

    标签: stack


    【解决方案1】:

    您的递归代码中没有停止条件。如果您的堆栈为空或您的临时变量等于堆栈的大小,您必须“返回”。

    if(st.empty() || temp==n)
    return;
    

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 2015-06-24
      • 2020-06-15
      • 2021-12-13
      • 1970-01-01
      • 2021-10-19
      相关资源
      最近更新 更多