Wednesday, April 25, 2012

Coding a function to copy a linked-list [C++]

I need to implement an auxilliary function, named copyList, having one parameter, a pointer to a ListNode. This function needs to return a pointer to the first node of a copy of original linked list. So, in other words, I need to code a function in C++ that takes a header node of a linked list and copies that entire linked list, returning a pointer to the new header node. I need help implementing this function and this is what I have right now.



Listnode *SortedList::copyList(Listnode *L) {

Listnode *current = L; //holds the current node

Listnode *copy = new Listnode;
copy->next = NULL;

//traverses the list
while (current != NULL) {
*(copy->student) = *(current->student);
*(copy->next) = *(current->next);

copy = copy->next;
current = current->next;
}
return copy;
}


Also, this is the Listnode structure I am working with:



struct Listnode {    
Student *student;
Listnode *next;
};


Note: another factor I am running into with this function is the idea of returning a pointer to a local variable.





No comments:

Post a Comment