1.9K
Copying an entire Linked List, means allocating new memory and copying all the data to the new location.
This requires traversing each node and copying its data to a new location, keeping the original data intact.
#include<stdio.h> struct node { int data; struct node * next; }; // implementing a function to copy a Linked List struct node * copyList(struct node * head) { // creating a new variable as a list struct node * list2 = (struct node *)malloc(sizeof(struct node)); //creating a temporary variable to traverse the new list struct node * temp = list2; while(head) { // assigning value temp -> data = head -> data; // move to the next node head = head -> next; // if the next node exists // we need to create a new memory space if(head) { struct node * temp2 = (struct node *)malloc(sizeof(struct node)); //point the next of the temp to this new location temp -> next = temp2; // move to the new location temp = temp -> next; } else { // since there is no next node // means end of the list temp -> next = NULL; } } //returning the pointer of the new list return list2; } struct node * addElement(struct node *head, int number) { struct node * temp = (struct node*)malloc(sizeof(struct node)); temp -> data = number; temp -> next = NULL; struct node * temp2 = head; while(temp2 -> next != NULL) temp2 = temp2 -> next; temp2 -> next = temp; return head; } // a function to print the list void printer(struct node * head) { while(head) { printf("%d ",head -> data); head = head -> next; } } int main(void) { //creating a list struct node * listHead = (struct node*)malloc(sizeof(struct node)); listHead->data = 1; listHead->next = NULL; listHead = addElement(listHead, 2); listHead = addElement(listHead, 3); listHead = addElement(listHead, 4); printer(listHead); struct node * copy_of_list = copyList(listHead); // print the new list printf("\n"); printer(copy_of_list); return 0; }
2 comments
This code is flawed..please execute your code once to make sure its right. You are just allocating the list2 every time, but losing track of the allocated memory location completely.
Hi Sai,
Thanks for your support and feedback. I have corrected the code and will take care of this in the future.
Here is the working demo of the code. Please have a look
http://ideone.com/NFGyMB
Comments are closed.