gpt4 book ai didi

c - 在链表错误中用字符串替换字符?

转载 作者:行者123 更新时间:2023-11-30 17:49:54 24 4
gpt4 key购买 nike

以下代码应该将包含单个字符的节点替换为从字符串转换为多个节点的链接列表:

node *replaceChar(node *head, char key, char *str)
{
node *nhead = head;

if (head == NULL)
return nhead;

if (str == NULL || strcmp(str, "") == 0)
{
if (head->data == key)
{
deleteN(head, key);
}
head->next = replaceChar(head->next, key, str);
}

if (head->data == key)
{

node* temp = head;
node* tail = temp->next;

head = temp->next;
free(temp);

head = stringToList_replace(str, tail);

}

head->next = replaceChar(head->next, key, str);

return nhead;
}

stringToList_replace 函数接受一个字符串并将其转换为链表,然后返回该链表的尾部:

node *stringToList_replace(char *str, node* tail)
{
node *head = malloc(sizeof(node));
int i;

if (str == NULL || strcmp(str, "") == 0)
return NULL;

for (i = 0; i < strlen(str); i++)
{
if (str[i] != '\0')
{
head->data = str[i];

if (str[i+1] != '\0')
{
head->next = malloc(sizeof(node));
head = head->next;
}
}
}

head->next = tail;

return head;
}

最后,deleteN 在链表中查找某个值(键)的所有实例并将其删除。

node* deleteN(node* head, char key)
{
if (head == NULL)
return NULL;

node* tail = deleteN(head->next, key);

if (head->data == key)
{
free(head);
return tail;
}

else
{
head->next = tail;
return head;
}

}

我的代码中还有一个打印函数,可以打印链接列表。我的代码的问题是,如果我从列表中删除一个值,然后尝试替换另一个值,则某些替换的值会被切断。

例如:

初始链表:

[E]->[l]->[d]->[e]->[r]->[NULL]

调用deleteN(head, e)来删除'e'的所有实例:

[l]->[d]->[r]->[NULL]

调用replaceChar(node,r,scrolls)以将“r”的所有实例替换为“scrolls”:

[l]->[d]->[r]->[o]->[l]->[l]->[s]->[NULL]

上面应该是:

[l]->[d]->[s]->[c]->[r]->[o]->[l]->[l]->[s]

如果我只是进行替换而不先删除,或者只是删除,甚至在删除之前进行替换,我会得到正确的输出。但是,每次我执行删除然后替换时,输出都会被切断。有什么想法吗?

最佳答案

调用replaceChar(node, r, test),并查看输出是什么。在

if (head->data == key)
{

您跳过初始节点。

关于c - 在链表错误中用字符串替换字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17580961/

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