0

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

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) 用 'scrolls' 替换所有 'r' 实例:

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

以上应该是:

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

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

4

1 回答 1

0

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

if (head->data == key)
    {

你跳过你的初始节点。

于 2013-07-10T21:18:45.010 回答