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.
- you don't need 2 malloc each element.
- you need keep both reference @ head of list , @ current copied element
- 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
Post a Comment