You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言单链表单节点存储多数据实现及代码运行异常排查

问题解答

1. 单链表节点存储多类型数据的说明

C语言的单链表节点完全可以存储多个不同类型的数据,实现方式就是你代码中用到的结构体:将需要存储的不同类型数据定义为结构体的成员,写入和访问时通过结构体的.或->运算符操作对应成员即可。

2. 代码问题排查

一共存在以下几处错误:

  • 形参类型错误:addNode函数的第二个参数要接收字符串,你定义的是char string(单个字符),应该改为char *string或char string[]
  • 字符串赋值错误:C语言字符串不能直接用=赋值,且你写的newNode->name[30] = string存在数组越界(name数组长度为30时有效下标是0~29),需要引入<string.h>头文件,用strcpy(newNode->name, string)完成字符串拷贝
  • 排序逻辑不完整:你交换节点数据时只交换了data整数值,没有交换对应的name字段,导致排序后数值和姓名不匹配
  • 输出格式错误:display函数的printf没有加换行符,且输出顺序和你预期的「姓名在前、数值在后」相反
  • 缺少必要头文件:用到strcpy需要引入<string.h>

3. 修正后的完整代码

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h>
   
struct node{  
    int data;  
    char name[30];
    struct node *next;  
};      
   
struct node *head, *tail = NULL;  
   
void addNode(int data, char *string) {  
    struct node *newNode = (struct node*)malloc(sizeof(struct node));  
    newNode->data = data;  
    strcpy(newNode->name, string);
    newNode->next = NULL;  
      
    if(head == NULL) {   
        head = newNode;  
        tail = newNode;  
    }  
    else {  
        tail->next = newNode;  
        tail = newNode;  
    }  
}  
   
void sortList() {  
    struct node *current = head, *index = NULL;  
    int temp;  
    char temp_name[30];
          
    if(head == NULL) {  
        return;  
    }  
    else {  
        while(current != NULL) {  
            index = current->next;  
            while(index != NULL) {  
                if(current->data > index->data) {  
                    // 同时交换数值和姓名
                    temp = current->data;  
                    current->data = index->data;  
                    index->data = temp;
                    strcpy(temp_name, current->name);
                    strcpy(current->name, index->name);
                    strcpy(index->name, temp_name);
                }  
                index = index->next;  
            }  
            current = current->next;  
        }      
    }  
}  
   

void display() {  
    struct node *current = head;  
    if(head == NULL) {  
        printf("List is empty \n");  
        return;  
    }  
    while(current != NULL) {  
        // 调整输出顺序,增加换行
        printf("%s - %d\n", current->name, current->data);  
        current = current->next;  
    }  
    printf("\n");  
}  
      
int main()  
{  
    char string1[10] = "Aaron";
    char string2[10] = "Baron";
    char string3[10] = "Carla";
    
    addNode(9, string1);  
    addNode(7, string2);  
    addNode(2, string3);   

    printf("Original list: \n");  
    display();  

    sortList();  
   
    printf("Sorted list: \n");  
    display();  
          
    return 0;  
}

4. 运行结果

运行修正后代码,输出的排序结果和预期完全一致:

Carla - 2
Baron - 7
Aaron - 9

内容的提问来源于stack exchange,提问作者Kaizuke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:06:06