The following code is supposed to replace a node that contains a single character with several a linked list of nodes converted from a string:
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 function takes a string and converts it to a linked list, then returns the tail of that linked list:
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;
}
Finally, deleteN finds all instances of a value (key) in a linked list and deletes them.
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;
}
}
I also have a print function in my code that prints the linked list. The problem with my code is that if I delete a value from the list and then try to replace another value, some of the replaced value gets cut off.
For example:
initial linked list:
[E]->[l]->[d]->[e]->[r]->[NULL]
called deleteN(head, e) to delete all instances of 'e':
[l]->[d]->[r]->[NULL]
called replaceChar(node, r, scrolls) to replace all instances of 'r' with 'scrolls':
[l]->[d]->[r]->[o]->[l]->[l]->[s]->[NULL]
The above should be:
[l]->[d]->[s]->[c]->[r]->[o]->[l]->[l]->[s]
I get the correct output if I just do a replacement without deleting first, or just a deletion, or even a replacement before a deletion. However, every time I do a deletion and then a replacement, the output gets cut off. Any ideas?