It's been a long time since I've implemented a linked list, much less a linked list with a dummy head. I've referred to my text books and various web pages with no surefire answer. Can anyone confirm that I'm implementing this code correctly?
This is in a .cpp file, it's the default constructor and copy constructor for a linked list class with a dummy head.
// default constructor, creates empty list
List::List() : m_size(0)
{
// Initialize a dummy head
m_headPtr = NULL;
m_headPtr = new ListNode;
m_headPtr->next = NULL;
}
// Copy Constructor
List::List(const List& source) : m_size(source.size)
{
// Copy the dummy head:
m_headPtr = new ListNode;
m_headPtr->next = source.m_headPtr->next;
// Create a new pointer which will be utilized to point
// to the final item in the new list, starting at the dummy head
ListNode *newPtr = m_headPtr;
// Traverse the old list using origPtr to point to items
// from the old list.
for (ListNode* origPtr = source.m_headPtr->next;
origPtr != NULL;
origPtr = origPtr->next)
{
newPtr->next = new ListNode; // Create a new node
newPtr = newPtr->next; // Move to the new node
newPtr->item = origPtr->item; // Copy contents into new node
}
// Set the final pointer to NULL
newPtr->next = NULL;
}
It *looks* ok, albeit with some useless lines of code (line 5 isn't needed and line 15 isn't
needed).
I would also consider have ListNode have either a default constructor or a constructor
that takes an item as a parameter and initializes its next field to NULL. This would
eliminate lines 7 and 33. Line 6 should be in the initializer list, as could line 14.
EDIT: Because you need a custom copy constructor, you also need to provide a
custom assignment operator.