Reputation: 591
The stack which I'm using is not empty and I did a check for that still getting segment fault. Let 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;
}
Upvotes: 0
Views: 95
Reputation: 122350
Here
if(st.top()!=s[i])
st.push(s[i]);
else if(st.top()==s[i] && st.empty()==false){
You check if the stack is empty, but you do that too late. At the point you call st.empty()
you already called st.top()
twice. You need to check if there is an element before you try to access it. I am not sure about the logic of the code, but I suppose in the first condition you want to push
into an empty stack, otherwise check if s[i]
equals top
:
if(st.empty() || st.top()!=s[i])
st.push(s[i]);
else if(!st.empty() && st.top()==s[i]){
Note that both ||
and &&
are short-circuiting. Hence in A || B
if A == true
then B
will not be evaluated. Similar in C && D
, if C == false
then D
will not be evaluated.
Upvotes: 3