How to add a node in a specific location?
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 *hea开发者_如何学JAVAd 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.
if (whereX->before != NULL)
whereX->before->after = temp;
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.
Let's say you have this list:
[Node1] <-> [WhereX] <-> [Node2]
From these assignments:
Node *temp = (Node*)malloc(sizeof(Node));
temp->count = who->count;
strcpy(temp->word,who->word);
temp->before = whereX->before;
temp->after = whereX;
and from this:
whereX->before = temp;
you will have:
[Node1] <- [temp] <-> [WhereX] <-> [Node2]
| ^
----------------------
but Node1's after
pointer is still looking at WhereX, so
you should also add this assignment:
whereX->before->after = temp;
What you are doing needs some changes. You have correctly allocated memory to duplicate. But problem statement is not very clear.
Assuming you want to add a node before whereX, you have to do the following:
- Point
"after"
pointer of temp to whereX - Point "before" pointer of temp to "
before
" pointer of whereX - Point "
before->after
" pointer of whereX to temp - Point "
before
" pointer of whereX to temp
Hope this helps.
EDIT:
Also do the appropriate NULL checks
精彩评论