首页 > 解决方案 > 堆栈弹出给出段错误

问题描述

我正在使用的堆栈不是空的,我检查了仍然出现段错误。让 s="aaabbaaccd"

string removePair(string s){
  stack<char>st;
  st.push(s[0]);                  //Doing this,So that first pop without insert doesn't cause error.
  string output="";
  for(int i=1;i<s.length();i++){
    if(st.top()!=s[i])
        st.push(s[i]);
    else if(st.top()==s[i] && st.empty()==false){
        st.pop();               //Gives Segment fault.
    }
  }
  while(st.empty()==false){
    output+=st.top();
    st.pop();
  }
  reverse(output.begin(),output.end());
  return output;
}

在此处查看完整代码

标签: c++stack

解决方案


这里

if(st.top()!=s[i])
    st.push(s[i]);
else if(st.top()==s[i] && st.empty()==false){

您检查堆栈是否为空,但为时已晚。在你打电话的时候,st.empty()你已经打电话st.top()了两次。在尝试访问它之前,您需要检查是否存在元素。我不确定代码的逻辑,但我想在第一个条件下你想push进入一个空堆栈,否则检查是否s[i]等于top

if(st.empty() || st.top()!=s[i])
    st.push(s[i]);
else if(!st.empty() && st.top()==s[i]){

请注意,两者||都是&&短路的。因此在A || Bif A == truethenB中不会被评估。类似C && D, if C == falsethenD不会被评估。


推荐阅读