C语言链表头部插入时分元素报错及功能异常求助
链表头部插入时分元素的问题修复
核心问题分析
- 函数参数不匹配:
insert_beginning声明仅接受3个参数,但调用时传入了4个(时分两个值),这是编译报错的直接原因。 - 链表指针逻辑混乱:冗余定义了
root1、root2两个链表根指针,实际只需一个链表存储时分对;且遍历使用未初始化的root指针,导致无输出。 - 条件判断错误:
if (option == '1')将整数option与字符'1'(ASCII码49)比较,永远无法进入分支,这是输入1后程序直接结束的关键原因。 - 插入逻辑错误:新节点的
hour和minute被赋值为同一个value,且两次对next赋值覆盖指针,完全不符合链表插入逻辑。
修复后的完整代码
#include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> typedef struct node{ int hour, minute; struct node* next; }node; // 调整参数:接收链表根指针、时分值,实现头部插入 void insert_beginning(node** root, int hour, int minute) { node* new_node = malloc(sizeof(node)); if (new_node == NULL) { exit(1); } new_node->hour = hour; new_node->minute = minute; // 头部插入逻辑:新节点指向当前根,更新根为新节点 new_node->next = *root; *root = new_node; } int main (int argc, char* argv[]) { int option = 0; node* root = NULL; printf("Choose option: \n"); printf("1. Add time to the list. \n"); printf("2. Delete time from the list. \n"); printf("3. Change the position of the biggest and the smallest elements. \n"); printf("4. Write the list. \n"); printf("5. Delete the list. \n"); printf("Your option: "); scanf("%i", &option); // 修正条件判断:整数1与字符'1'的区别 if (option == 1) { insert_beginning(&root, 12, 15); insert_beginning(&root, 13, 20); insert_beginning(&root, 14, 25); // 遍历链表:头部插入后,最后插入的元素在链表头部,自然逆序输出 for (node* curr = root; curr != NULL; curr = curr->next) { printf("%d:%d\n", curr->hour, curr->minute); } } return 0; }
修复关键点
- 调整
insert_beginning函数参数,适配时分值的传入需求,简化为维护单个链表根指针。 - 修正条件判断逻辑,确保输入整数1时能进入对应处理分支。
- 修复链表插入逻辑,正确维护节点的
next指针关系,实现头部插入。 - 遍历使用初始化后的
root指针,利用头部插入特性实现逆序输出预期效果。
内容的提问来源于stack exchange,提问作者Lvrnnk
相关产品推荐
相关产品推荐

