Function to make a deep copy of a LinkedList C++
I have a function to make a deep copy of a linkedlist:
void LinkedList::copyData(Node* sourcePtr, Node*& headPtr, Node*& tailPtr)
{
int currentData = 0;
if (sourcePtr == NULL)
{
return;
}
headPtr = NULL;
tailPtr = NULL;
headPtr = new Node(sourcePtr->getData(), headPtr);
tailPtr = headPtr;
sourcePtr = sourcePtr->getNextPtr();
while (sourcePtr != NULL)
{
currentData = sourcePtr->getData();
insert(tailPtr, currentData);
sourcePtr = sourcePtr->getNextPtr();
}
} //end function
where sourcePtr is the head pointer of a list to 开发者_如何学Pythonbe copied, and headPtr and tailPtr are the pointers of a list that are going to be replaced with the list from sourcePtr.
I need to use the & for the head and tail as the linkedlist is being replace and all data must be removed.
In the program I call:
list1.copyData(list2.getHeadPointer(), list1.getHeadPointer(), list1.getTailPointer());
Where list1 and list2 are arrays of int array1[3] = {1, 2, 3} and array2[3] = {4, 5, 6}.
The above does not work as the functions do not match.
getHeadPointer() and getTailPointer() both return the address of a pointer.
Node* LinkedList::getHeadPointer()
{
return headPtr;
}
but to satisfy the function should I be adding &'s inside, how would I do this?
list1.copyData(list2.getHeadPointer(), list1.getHeadPointer()&, list1.getTailPointer()&);
Currently the classes are node class -> linkedlist class -> random class -> program
random class will be using instances of linkedlist so i need to be able to call the copyData function without randomclass knowing about nodes.
I hope that makes some sense of what I am trying to do.
The function
void LinkedList::copyData(Node* sourcePtr, Node*& headPtr, Node*& tailPtr)
appears to be a static
member of LinkedList
.
However the designed seems be botched, so one can't be sure (and you don't say anything more about this).
Assuming that it's a static
member then it can probably be called like this:
void foo( Node* source )
{
Node* newHead;
Node* newTail;
LinkedList::copyData( source, newHead, newTail );
// Now use the pointers to the copy.
}
Since it's botched there is, however, also a good chance that the above call will NOT work. For example, that the destination list must be created first. Only you, the OP, can know that, because only you have the code and specification of this thing.
It is, essentially, backwards to ask others how to call the function.
You're the only one in a position to know; we can only guess, very roughly.
Cheers & hth.,
Looks like you misunderstand the pass by reference semantics. Assign those pointers to variables of type Node*
first before passing them to the function, and pass them naturally (i.e. without any additional symbols):
Node *hp2 = list2.getHeadPointer();
Node *hp1 = list1.getHeadPointer();
Node *tp1 = list1.getTailPointer();
list1.copyData(hp2,hp1,tp1);
精彩评论