The homework question basically asks to write a function to copy a Linear Linked
ID: 3624306 • Letter: T
Question
The homework question basically asks to write a function to copy a Linear Linked List to form a new Linear Linked List.
It is separated into two parts, one assumes the data in the nodes of the first linear linked list is an integer whilst the second part it assumes the data in the nodes are dynamically allocated array of characters.
I know I must create a new pointer for the new array and traverse through the first linked list one node at a time and make a copy of that node to the second list. I'm stuck on how I could write the proper code for it.
Explanation / Answer
Dear user, Here is the code to a function to copy a linear linked list to form a new linear linked list: template<class Type> Void linkedListType<Type>::copyList(const linkedListType<Type> &otherList) { nodeType<Type> *newNode; //Pointer to create a node nodeType<Type> *current; //pointer to traverse the lest if(first!=NULL) //If the list is nonempty, make it empty destroyList( ); if(otherList.first==NULL) //otherList is empty { first=NULL; last=NULL; count=0; } else { current=otherList.first; //current points to the list to be copied count=otherList.count; //Copy the first node first=new nodeType<Type> //create the node first->info=current->info //copy the info first->link=NULL; //set the link field of the node to NULL last=first; //make current point to the next node current=current->link; //make current point to the next node //copy the remaining list while(current!=NULL) { newNode=new nodeType<Type> //create a node newNode->info=current->info; //copy the info newNode->link=NULL; //set the link of newNode to NULL last->link=newNode; //attach newNode after last last=newNode; //make last point to the actual last node current=current->link; //make current point to the next node } } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.