I have a linked list comprised of chars like so...
node1 - "p"
node2 - "o"
node3 - "p"
I need a function that will take in three perameters...
node *replaceChar(node *head, char key, char *str)
Stipulations of this function. head is the head of the list, 'key' and 'str' are guaranteed to contain alphanumeric characters only (A-Z, a-z, and 0-9). str can range from 1 to 1023 characters (inclusively).
So if I call this function with these perameters..
node *head == /*the head of the list to be examined*/
char key == "p"
char *str == "dog"
The new list will look like this...
node1 - 'd'
node2 - 'o'
node3 - 'g'
node4 - 'o'
node5 - 'd'
node6 - 'o'
node7 - 'g'
All instances of 'p' were replaced with 'dog'
I have a toString function which takes in a string and converts it to a linked list and returns the head. So assume that you can call the function on str = "dog" so...
toString(str) == /*this will return the head to the list made from the str*/
If it's unclear what my question is...I am stumped on how to write the replaceChar function the one that takes in three perameters.. I can create a new list using the string and find all instances of key but making the new list fit into the old list without losing the pointers is killing me.
I HAVE TRIED THIS...
while(head->data != NULL)
{
if(head->data == key)
{
node *newListHead = toString(str);
head = newListHead;
/*here I lose track of the old list*/
You can start like this:
node *replaceChar(node *head, char key, char *str)
{
node *cur, prev;
for (cur = head, prev = NULL; cur != NULL; prev = cur, cur = cur->next)
if (cur->ch == key) {
node *hstart = toString(str);
for (node *hend = hstart; hend->next != NULL; hend = hend->next)
;
if (prev == NULL)
head = hstart;
else
prev->next = hstart;
hend->next = cur->next;
free(cur);
}
}
My assumptions: Your node struct is like:
sturct node {
char ch;
struct node* next;
};
toString(str)
works perfectly fine.