Vivian Maya
Vivian Maya

Reputation: 518

Why does this pointer get assigned while copying a linked list?

In this code:

Node *CopyList(Node **head) {
    Node *current = *head;
    Node *NewNode = NULL;
    Node *tail = NULL;

    while (current != NULL ) {
        if (NewNode == NULL) {
            NewNode = malloc(sizeof(Node));
            NewNode->data = current->data;
            NewNode->next = NULL; // routine
            tail = NewNode;
        } else {
            tail->next = malloc(sizeof(Node)); // here 
            tail = tail->next;
            tail->data = current->data;
            tail->next = NULL;
        }
        current = current->next;
    }
    return(NewNode);
}

Why are we assigning tail->next to the result of a malloc() call? Evidently, if we don't do so a segmentation fault occurs.

Why didn't we just allocate tail instead of tail->next? What are some situations in which I should allocate next like this?

Upvotes: 1

Views: 54

Answers (2)

2501
2501

Reputation: 25752

It is just a convenience, to avoid an extra variable:

Node* temp = malloc(sizeof(Node)); // here 
temp->data = current->data ;
temp->next = NULL ;

tail->next = temp ;
tail = tail->next;

Why we didn't just allocate tail instead tail->next ?

Tail is already allocated, it is acting as the previous node, so we can link it to the next one. We allocate a new node and link tail to that node with tail->next = that_node.

Upvotes: 2

kriyeta
kriyeta

Reputation: 705

here NewNode represents New Linked list head. So for the first time in while loop it gets allocated so it's not getting changed next time onward. Coming to your question that 'tail->next' instead of 'tail' because for the first time when 'NewNode == NULL' then 'tail = NewNode' gets executed means tail is having NewNode address. So next onward you need to copy next block into 'tail->next' as tail is already having 'NewNode'.

Upvotes: 1

Related Questions