C++链表存储表达式字符串遇内存问题:末尾操作数丢失原因?
问题分析:表达式转链表丢失最后一个操作数的原因及修复方案
我一眼就看出问题所在了——你的strTolist函数漏掉了处理表达式末尾的操作数!
错误根源
当处理类似"9+1"这样的表达式时,函数的while循环只会在遇到运算符的时候,才会把之前积累的操作数字符串(Stroper)转成链表节点。但如果表达式是以操作数结尾的,循环结束后,最后一段操作数字符串根本没被处理,自然就不会生成对应的节点,导致输出丢失最后一个操作数。
举个具体的执行流程:
- 处理字符
'9':添加到Stroper,此时Stroper = "9"; - 处理字符
'+':检测到是运算符,把"9"转成float并创建操作数节点,接着创建'+'的运算符节点,清空Stroper; - 处理字符
'1':添加到Stroper,此时Stroper = "1"; - 循环结束(
i等于字符串长度3),但Stroper里的"1"没有被转成节点,链表就少了这一项。
修复方案
在while循环结束后,额外检查Stroper是否不为空,如果有剩余内容,就把它转成float并添加到链表中。修改后的strTolist函数如下:
void strTolist(string str,LinkEXP &E) // here is the most important function { LinkEXP r = E; string Stroper; // Stroper will store the operand(string type) float Floper; // Floper will store the operand(float type) int i = 0; while(i<str.length()) { if(!isOprAll(str[i])) { Stroper = Stroper + str[i]; } else { if(Stroper.length()!=0) { Floper = atof(Stroper.c_str()); // turn the string type operand to float type operand r->next = new EXPnode; // add the operand to the node r = r->next; r->next = NULL; r->operand = Floper; r->judge = false; } Stroper = ""; r->next = new EXPnode; // add the operation to the node r = r->next; r->next = NULL; r->operation = str[i]; r->judge = true; } i++; } // 新增:处理循环结束后剩余的操作数 if(Stroper.length() != 0) { Floper = atof(Stroper.c_str()); r->next = new EXPnode; r = r->next; r->next = NULL; r->operand = Floper; r->judge = false; } }
测试验证
修改后运行代码,ListOutput函数就能正确输出预期的内容(注:你当前的输出语句是直接拼接字符串和数字,会显示here should be 99,可以改成cout<<"here should be 9: "<<p->operand<<endl;让格式更清晰)。
内容的提问来源于stack exchange,提问作者Chor
相关产品推荐
相关产品推荐

