tags:

views:

44

answers:

3

Hello,

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?

+1  A: 

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;
Thanks for your answer!
Y_Y
+2  A: 

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.

what if I don't want to return the new head and I have a Node *head as a global variable. how can I fix the flaw?
Y_Y
With a global variable holding the head, you'd need to free() the old head and then point it to the new one.
M... That is interesting. The global variable 'head' that I have just points to the first node of the list and the last node of the list so 'whereX' nor 'who' will never be head. Is kinda like a bridge.
Y_Y
A: 

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:

  1. Point "after" pointer of temp to whereX
  2. Point "before" pointer of temp to "before" pointer of whereX
  3. Point "before->after" pointer of whereX to temp
  4. Point "before" pointer of whereX to temp

Hope this helps.

EDIT:

Also do the appropriate NULL checks

Praveen S