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

C语言字符串双向链表问题:插入字符串仅输出首字符ASCII值

C语言双向链表存储字符串问题解决建议

你的问题根源在于链表节点只能存储单个字符,而非完整字符串:

  • 结构体里的char e只能存一个字符,所以插入"Joe"时实际只传入了首字符'J';
  • 显示函数用%d输出,自然打印出'J'的ASCII值74。

以下是具体修正步骤和代码:

1. 修改链表节点结构

把单个字符成员改成字符串存储容器,可选两种方案:

方案1:动态分配字符串指针(灵活,适合不确定字符串长度的场景)

typedef struct Item *Position;
typedef struct Item *List;

struct Item
{
    char *str;          // 用指针存储字符串,后续动态分配内存
    Position previous;
    Position next;
};

方案2:固定长度字符数组(简单,适合已知最大字符串长度的场景)

typedef struct Item *Position;
typedef struct Item *List;

struct Item
{
    char str[100];      // 固定长度数组,需确保输入字符串不超过99字符(留1位存结束符)
    Position previous;
    Position next;
};

2. 修正Insert函数

调整参数为字符串类型,同时处理字符串的内存分配与复制:

对应方案1的Insert函数

#include <string.h>  // 需要引入string.h使用strlen、strcpy

void Insert(const char *x, List l, Position p)
{
    Position TmpCell = (struct Item*) malloc(sizeof(struct Item));
    if(TmpCell == NULL)
    {
        printf("Memory out of space\n");
        return;
    }

    // 为字符串分配内存:长度=输入字符串长度+1(存储'\0'结束符)
    TmpCell->str = (char*) malloc(strlen(x) + 1);
    if(TmpCell->str == NULL)
    {
        printf("Memory out of space for string\n");
        free(TmpCell);  // 避免内存泄漏,先释放节点内存
        return;
    }

    // 复制字符串,这里用strcpy即可;如果要限制长度,可改用strncpy
    strcpy(TmpCell->str, x);

    // 调整双向链表指针
    TmpCell->previous = p;
    TmpCell->next = p->next;
    if(p->next != NULL)  // 若插入位置不是链表末尾,需修改下一个节点的前驱指针
    {
        p->next->previous = TmpCell;
    }
    p->next = TmpCell;
}

对应方案2的Insert函数(用strncpy避免数组溢出)

#include <string.h>

void Insert(const char *x, List l, Position p)
{
    Position TmpCell = (struct Item*) malloc(sizeof(struct Item));
    if(TmpCell == NULL)
    {
        printf("Memory out of space\n");
        return;
    }

    // 用strncpy限制复制长度,确保不超过数组大小,手动添加结束符
    strncpy(TmpCell->str, x, 99);
    TmpCell->str[99] = '\0';

    // 调整双向链表指针
    TmpCell->previous = p;
    TmpCell->next = p->next;
    if(p->next != NULL)
    {
        p->next->previous = TmpCell;
    }
    p->next = TmpCell;
}

3. 修正Display函数

把输出格式符从%d改成%s,用于打印字符串:

void Display(List l)
{
    printf("The list elements are :: ");
    Position p = l->next;
    while(p != NULL)
    {
        printf("%s -> ", p->str);
        p = p->next;
    }
    printf("NULL\n");  // 标记链表末尾
}

额外注意事项

  • 如果使用动态指针方案,销毁链表时要先释放每个节点的str内存,再释放节点本身,避免内存泄漏;
  • 调用Insert函数时,直接传入完整字符串即可,比如Insert("Joe", list, somePosition);,无需拆分单个字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:25:53