gpt4 book ai didi

c - 插入链表无法正常工作

转载 作者:行者123 更新时间:2023-11-30 15:43:42 26 4
gpt4 key购买 nike

我想为我的链接列表添加一个插入方法,该方法将插入到链接列表中已有的内容(附加值)。

现在这是我的代码:

struct node {
char value;
struct node *next;
};

typedef struct node item;

void main() {
InsertChar('a');
InsertChar('b');
InsertChar('c');
}

void InsertChar(char s) {
item *curr, *head;

head = NULL;

curr = (item *)malloc(sizeof(item));
curr->value = s;
curr->next = head;
head = curr;

while(curr) {
printf("%c", curr->value);
curr = curr->next;
}

printf("\n");
}

问题是在控制台中打印

a 
b
c

我需要它来打印类似的东西

a
ab
abc

在 main() 中调用 3 个 InsertChar 方法后。

我该怎么做?

最佳答案

你的问题是 head 是在函数中本地声明的,当你离开函数时,你就失去了它。当您再次访问该函数时,您将从头开始创建它,等等。

因此您需要将 head 作为参数传递给 InsertChar 函数。

此外,如果您想查看 a、ab、abc 输出,您需要将元素添加到列表的尾部,而不是像现在一样添加到头部。为了实现这一点,您要么需要为 tail 存储一个单独的指针,要么每次遍历到最后一个元素。

关于c - 插入链表无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19779743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com