基于双向链表的支出管理器:无法获取最大消费日期及插入异常求助
双向链表支出管理器的问题排查与修复
我来帮你逐个排查并修复这两个问题:
1. 查找最大消费节点崩溃的问题
你的maximumNode函数崩溃的核心原因是使用了未初始化的野指针:struct node *max;声明后没有指向任何有效的节点内存,直接访问max->total会触发未定义行为(程序崩溃)。
你需要让max一开始就指向链表的头节点,然后遍历链表时,只要遇到总额更大的节点,就更新max的指向(而不是直接修改max->total的值)。修复后的函数如下:
void maximumNode() { struct node *new1 = start; struct node *max; if(start == NULL) { printf("List is empty\n"); return; } // 初始化max指向头节点,避免野指针 max = start; while(new1 != NULL) { if(new1->total > max->total) { // 找到更大的总额时,更新max为当前节点 max = new1; } new1 = new1->right; } printf("The maximum spending was: %d and the day was: %d\n\n",max->total, max->day); }
2. 链表插入功能的错误
你的Insert函数在处理非空链表时犯了两个致命错误:
- 错误地将新节点的数据赋值给了头节点
start,直接覆盖了原有头节点的所有数据; - 新创建的节点
t完全没有被赋值,插入的是垃圾数据。
修复后的插入函数如下,我标注了关键修改点:
void Insert(int a, int b, int c, int d) { struct node *temp,*t; int total1 = b + c + d; temp = (struct node*)malloc(sizeof(struct node)); if(start == NULL) { start = temp; start->day = a; start->movies = b; start->groceries = c; start->travel = d; start->total = total1; start->left = NULL; start->right = NULL; printf("%d", total1); } else { // 遍历找到链表的尾节点 temp = start; while(temp->right != NULL) { temp = temp->right; } // 创建新节点并赋值(原来错误地赋值给了start) t = (struct node*)malloc(sizeof(struct node)); t->day = a; t->movies = b; t->groceries = c; t->travel = d; t->total = total1; // 建立双向链接 t->right = NULL; t->left = temp; temp->right = t; } printf("\n\nYour expense has been saved successfully!\n\n"); }
额外注意事项
别忘了在所有函数外部正确声明全局变量start,否则会出现未定义行为:
struct node *start = NULL;
内容的提问来源于stack exchange,提问作者Bladarc
相关产品推荐
相关产品推荐

