Below is the working function for copying the link list, by just passing the address of the original link list to this function it will create a copy and return the head.
I didn't understand how memory is assigned to tail->next pointer and how it is still pointing to the head_copy pointer. tail = tail->next; Now tail points to the new memory which is allocated to it using malloc, but still it points to the head_copy.
can anyone help me in understanding the flow of this code.
struct node
{
int data;
struct node* next; //Pointing back to the same structure.
};
struct node* copy_link_list(struct node** head)
{
struct node* head_copy = NULL;
struct node* tail = NULL;
while (*head != NULL)
{
//printf("data in copy is %d and local_variable addr is %p\n",temp->data,&local);
if (head_copy == NULL)
{
head_copy = malloc(sizeof(struct node));
head_copy->data = (*head)->data;
head_copy->next = NULL;
tail = head_copy;
}
else
{
//printf("1. tail /// tail_of_data /// tail_of_next %p %d %p\n",&tail,tail->data,&(tail->next));
printf("head_copy head_copy_of_data and head_copy_of_next %p %d %p\n",&head_copy,head_copy->data,(head_copy->next));
tail->next = malloc(sizeof(struct node));
printf("2. tail /// tail_of_data /// tail_of_next %p %d %p %p\n",&tail,tail->data,&(tail->next),tail->next);
tail = tail->next;
printf("3. tail /// tail_of_data /// tail_of_next %p %d %p %p\n",&tail,tail->data,&(tail->next),tail->next);
tail->data = (*head)->data;
tail->next = NULL;
}
*head = (*head)->next;
}
return head_copy;
}
if (head_copy==NULL)setstailto point to the a copy of the first node (assuming a non-empty list). After, at the beginning of theelseblock,tailalways points to the last "node" which was copied, the a new node is assigned/created attail->next, filled by copying the data. So now,tail->nextis the last node which was copied, that is whytail = tail->next(because as stated above,tailshould always point to the last node copied). - Emil Vatai