Hi, Please help me out.. I\'m studying for my finals and need help in writing th
ID: 3659413 • Letter: H
Question
Hi, Please help me out.. I'm studying for my finals and need help in writing the following code in C++.
Please write a function called:
Explanation / Answer
A simple linked list copy::: struct node* copy_list(struct node *root) { struct node *res=NULL; struct node *cur = root; struct node *next, *tmp; //Create the copy of every node in the list and insert //it in original list between current and next node. while(cur) { tmp =(struct node *)malloc(sizeof(struct node)); tmp->val = cur->val; tmp->random = NULL; tmp->next = cur->next; next = cur->next; cur->next = tmp; cur = next; } //save result pointer res = root->next; //Copy the arbitrary link for result cur = root; while(cur) { cur->next->random = cur->random->next; cur = cur->next->next; //move 2 nodes at a time } //restore the original and copy linked lists cur = root; tmp = root->next; while(cur && tmp) { cur->next = cur->next->next; cur = cur->next; if (tmp->next){ tmp->next = tmp->next->next; tmp = tmp->next; } } return res; }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.