Reputation: 13
I wrote a function that copies a linked list. Unfortunately it doesn't copy the list completely.
Node *copy(Node *list)
{
Node *copy2;
while(list != NULL) {
copy2 = malloc(sizeof(Node));
memcpy(copy2,list,sizeof(Node));
list = list->next;
if(list != NULL) {
copy2->next = malloc(sizeof(Node));
copy2 = copy2->next;
}
}
return copy2;
}
Upvotes: 1
Views: 2734
Reputation: 1524
It gives you only the last element and it also has lots of memory leaks.
Try this.
Node *copy(Node *list)
{
Node *newList = NULL;
Node **newIt = &newList;
while(list!=NULL)
{
*newIt = malloc(sizeof(Node));
memcpy(*newIt,list,sizeof(Node));
list = list->next;
newIt = &((*newIt)->next);
}
return newList;
}
Upvotes: 3
Reputation: 5826
Here is C++ code for coping linked list to another linked list
struct Node {
int value;
Node* next;
};
Node* copy(Node* list) {
if (list == NULL) return NULL;
Node* result = new Node;
result->value = list->value;
result->next = copy(list->next);
return result;
}
Upvotes: 0
Reputation: 3188
You have 2 major bugs here:
You don't store the head of the copied list. Anywhere. And when you return copy2
you return a pointer to the last element of the list and forever lose the reference to the list head.
copy2
isn't dynamically allocated and will be deallocated when your function exits. This will likely lead to a segmentation fault if you fix issue 1.
Upvotes: 2