template<typename NODETYPE>
const List<NODETYPE> &List<NODETYPE>::operator =(const List<NODETYPE> &right)
{
if(&right !=this)
//ListNode is another class I friended with my list class
{
ListNode<NODETYPE> *tempPtr = firstPtr;
ListNode<NODETYPE> *rightPtr = right.firstPtr;
if(firstPtr==lastPtr)
{
firstPtr = lastPtr = 0;
delete tempPtr;
while(rightPtr!=NULL)
{
insertAtBack(rightPtr->data);
rightPtr=rightPtr->nextPtr;
}
}
else
{
while(tempPtr!=NULL)
{
firstPtr = firstPtr->nextPtr;
delete tempPtr;
tempPtr = firstPtr;
}
while(rightPtr!=NULL)
{
insertAtBack(rightPtr->data);
rightPtr=rightPtr->nextPtr;
}
}
}
return *this;
}
template<typename NODETYPE>
List<NODETYPE>& List<NODETYPE>::concatenate(const List<NODETYPE>&right)const
{
ListNode<NODETYPE>*tempPtr = firstPtr;
我在这里使用了 new 运算符,因此当我返回它时不会调用对象的析构函数。我想创建一个由两个列表组成的全新 List 对象并将其返回给主函数,同时避免任何内存泄漏。
List<NODETYPE>*newList = new List;
while(tempPtr != NULL)
{
newList->insertAtBack(tempPtr->data);
tempPtr = tempPtr->nextPtr;
}
tempPtr = right.firstPtr;
while(tempPtr != NULL)
{
newList->insertAtBack(tempPtr->data);
tempPtr = tempPtr->nextPtr;
}
return *newList;
}
如何在不造成内存泄漏的情况下返回 newlist 对象?
template< typename NODETYPE >
void List< NODETYPE >::insertAtBack( const NODETYPE &value )
{
ListNode< NODETYPE > *newPtr = getNewNode( value ); // new node
if ( isEmpty() ) // List is empty
firstPtr = lastPtr = newPtr; // new list has only one node
else // List is not empty
{
lastPtr->nextPtr = newPtr; // update previous last node
lastPtr = newPtr; // new last node
} // end else
} // end function insertAtBack
template< typename NODETYPE >
void List< NODETYPE >::insertAtPos( const NODETYPE & value, int pos)
{
if (pos == 0)
insertAtFront(value);
else if (pos < 0)
cerr << "Trying to insert at invalid list position: " << pos << endl;
else {
ListNode< NODETYPE > * ptr = firstPtr;
for (int i=0; i<pos-1 && ptr != NULL; i++)
ptr = ptr->nextPtr;
if (ptr != NULL) {
ListNode< NODETYPE > *newPtr = getNewNode( value ); // new node
newPtr->nextPtr = ptr->nextPtr;
ptr->nextPtr = newPtr;
}
else {
cerr << "Trying to insert at invalid list position." << endl;
}
}
}