Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function with the following prototype struct node* copyList (struct node

ID: 3858875 • Letter: W

Question

Write a function with the following prototype struct node* copyList (struct node* list) The struct node is the same used in question 18, The function should create a new, separate copy of the linked list pointed to by the list parameter and return a pointer to the head the newly created linked list copy.

Explanation / Answer

The required source code is as follows- Comments present for explanation. struct __Element__ { int info; struct __Element__ *next; }; typedef struct __Element__ node; struct node *copyList(struct node *List) //function defintion { //function definition begins node* L2 = NULL; node* preElem = NULL; //Iterate through all the nodes present in source list. while(List != NULL) { //while loop begins // Dynamically allocate memory for the destination list node. struct node *elem = (node*)malloc (sizeof(node)); if(elem == NULL) { printf("Failed allocation!"), exit(1); } // Copy the data from the source to destination node elem->info = List->info; elem->next = NULL; if (L2 == NULL) { // keep the head node for the destination list. L2 = elem; preElem = elem; } else { // point the new node to the previous node. preElem->next = elem; // keep new node and use it as previous node when we create next node. preElem = elem; } //while loop ends List = List->next; } return L2; } //function definition ends

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote