C语言链表按num_id排序后姓名与课程字段不匹配问题求助
问题原因定位
- 交换逻辑完全错误:你当前的排序逻辑将三个字段的交换拆分到了独立的
if/else if分支中,仅当num_id不需要交换时才会判断name,仅当num_id和name都不需要交换时才会判断lesson,且每次分支只会交换单个字段的值,导致num_id交换到正确位置后,对应的name和lesson仍留在原节点,和新的num_id不匹配,这是你输出结果中num_id顺序正确但其余字段错位的核心原因。 - 字符串比较逻辑错误:C语言中直接用
>比较字符数组名,实际比较的是两个字符串的内存首地址,而非字符串的字典序,需要使用标准库函数strcmp完成字符串内容比较。 - 插入函数字段名不匹配:结构体定义的学号字段是
num_id,但push_data函数中赋值时错误写为current->nim,会导致字段赋值异常,属于笔误。 - 野指针风险:插入新节点时没有将新节点的
link指针初始化为NULL,可能导致后续遍历链表时出现非法内存访问。
修正后的排序函数代码
#include <string.h> // 需引入strcmp、strcpy对应的头文件 void linked_list_sorted() { struct nodes *node, *temp_sorted; int temp_num_id, count_data=0; char temp_name[30], temp_lesson[30]; node = head; while(node != NULL) { temp_sorted = node; while (temp_sorted->link != NULL) { // 按num_id升序排序,需要交换时同步交换三个字段 if(temp_sorted->num_id > temp_sorted->link->num_id) { // 交换num_id temp_num_id = temp_sorted->num_id; temp_sorted->num_id = temp_sorted->link->num_id; temp_sorted->link->num_id = temp_num_id; // 交换name strcpy(temp_name, temp_sorted->name); strcpy(temp_sorted->name, temp_sorted->link->name); strcpy(temp_sorted->link->name, temp_name); // 交换lesson strcpy(temp_lesson, temp_sorted->lesson); strcpy(temp_sorted->lesson, temp_sorted->link->lesson); strcpy(temp_sorted->link->lesson, temp_lesson); } // 若需要num_id相同时按name字典序排序,可补充以下逻辑: // else if(temp_sorted->num_id == temp_sorted->link->num_id && strcmp(temp_sorted->name, temp_sorted->link->name) > 0) // { // // 同样同步交换三个字段即可 // } temp_sorted = temp_sorted->link; } node = node->link; } // 输出逻辑保持不变 temp_sorted = head; while(temp_sorted != NULL) { count_data++; printf("%d. %d - %s - %s\n", count_data, temp_sorted->num_id, temp_sorted->name, temp_sorted->lesson); temp_sorted = temp_sorted->link; } }
修正后的插入函数代码
void push_data (int nim, char name[], char lesson[]) { current = (struct nodes*)malloc(sizeof(struct nodes)); // 修正字段名错误,结构体字段为num_id current->num_id = nim; strcpy(current->name, name); strcpy(current->lesson, lesson); current->link = NULL; // 初始化新节点的next指针为空,避免野指针 if (head == NULL){ head = tail = current; } else if (current->num_id < head->num_id) { current->link = head; head = current; } else{ tail->link = current; tail = current; } }
内容的提问来源于stack exchange,提问作者MADFROST
相关产品推荐
相关产品推荐

