c++ - 堆栈弹出给出段错误
问题描述
我正在使用的堆栈不是空的,我检查了仍然出现段错误。让 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;
}
解决方案
这里
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 || B
if A == true
thenB
中不会被评估。类似C && D
, if C == false
thenD
不会被评估。
推荐阅读
- c++ - VS Code 使用 Ctrl - Alt - M 终止任务将不起作用
- identity - 尝试在 Blazor WASM 应用程序中搭建身份页面时出错
- ansible - Ansible Jinja2 Filter - 过滤数据并从数据创建列表
- java - 尝试运行 spring mvc-hibernate 应用程序时出现异常
- python - Django:如何在对称的多对多关系中获取引用对象?
- python - 将颜色过滤器添加到 Tk.Label
- c++ - 如何使用 MinGw G++ 编译器增加堆栈大小?
- laravel - 是否可以将 2 个变量传递给 View Composers 中的视图?
- java - MongoDB 4.4、Java 驱动程序 4.2.3 - InsertManyResult.getInsertedIds() 不返回所有插入文档的 ID
- sumo - 如何在当前的 SUMO 场景中添加额外的路线?