I have been working with a doubly linked list. Everything works OK with the exemption of the function that should add a copy of ‘who’ before ‘whereX’ [see code bellow]. Why is the function not working?
void addNodeAt(Node *whereX, Node *who)
{
//copy
Node *temp = (Node*)malloc(sizeof(Node));
temp->count = who->count;
strcpy(temp->word,who->word);
temp->before = whereX->before;
temp->after = whereX;
//paste
if(whereX->after == who)
whereX->after = who->after;
whereX->before = temp;
}
EDIT:
In response to user326404 who said:
‘Note: Your function does suffer a flaw that prevents it from inserting who as the new head of the list. It will insert, but you never return the new head node so the list is lost.’
what if I have a Node *head as a global variable. How can I reasign the head without returning it?
You are not letting the existing links know about the newly created temp node. Add the following code to the end of the function to let the preceding portion of the chain point to the newly created node.
Note: Your function does suffer a flaw that prevents it from inserting
whoas the new head of the list. It will insert, but you never return the new head node so the list is lost.