Dummy Head in a Linked List? Am I doing this right?

Feb 6, 2010 at 1:11am
Greetings!

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 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;
}




Thanks!
Feb 6, 2010 at 1:37am
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.
Last edited on Feb 6, 2010 at 1:37am
Topic archived. No new replies allowed.