Copying Linked List in C -


i wrote function copies linked list. unfortunately doesn't copy 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; } 

it gives last element , has lots of memory leaks.

  1. you don't need 2 malloc each element.
  2. you need keep both reference @ head of list , @ current copied element
  3. you need keep pointer reference change pointer inside 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; } 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -