user3386053
user3386053

Reputation: 13

Copying Linked List in C

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

Answers (3)

ARLabs
ARLabs

Reputation: 1524

It gives you only the last element and it also has lots of memory leaks.

  1. You don't need two malloc for each element.
  2. You need to keep both reference at the head of the list and at the current copied element
  3. You need to keep the pointer to reference to change the pointer inside the previous node.

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

Rahul R Dhobi
Rahul R Dhobi

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

immortal
immortal

Reputation: 3188

You have 2 major bugs here:

  1. 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.

  2. 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

Related Questions