Asking for help in writing the copylist, copy constructor & operator= for a doublyLinkedList

here is the output that I get when I run the program:
Enter integers ending with -999
23 65 34 72 12 82 36 55 29 -999

List 1: 12 23 29 34 36 55 65 72 82
List 2: -2084468398
Enter the number to be deleted: 34

The item to be deleted is not in the list
After deleting the node, List 2:
-2084468398

Process returned 0 (0x0) execution time : 69.352 s
Press any key to continue.

The code is quite long so I selected the problematic function: copyList, copy constructor and operator=

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  template<class Type>
void doublyLinkedList<Type>::copyList
            	      (const doublyLinkedList<Type>& otherList)
{
   nodeType<Type> *next; //pointer to create a node
   nodeType<Type> *back; //pointer to traverse the list

   if(next != NULL)	//if the list is nonempty, make it empty
	  destroy();

		first = new nodeType<Type>;  //create the node

 		assert(first != NULL);

		first->info = next->info; //copy the info
		first->next = NULL;  	     //set the link field of
									 //the node to NULL
		last = first;    		     //make last point to the
            						 //first node
}//end copyList 


1
2
3
4
5
6
7
8
9
10
11
//copy constructor
template<class Type>
doublyLinkedList<Type>::doublyLinkedList
            	      (const doublyLinkedList<Type>& otherList)
{
	first = NULL;

	copyList(otherList);

}//end copy constructor

template<class Type>
const doublyLinkedList<Type>& doublyLinkedList<Type>::operator=
(const doublyLinkedList<Type>& otherList)
{
if(this != &otherList) //avoid self-copy
copyList(otherList);

return *this;
}
[/code]
In copyList, line 8 access the uninitialized local variable defined at line 5, resulting in undefined behavior.

My advice is to create a doublyLinkedList::validate(). This function will go through the list and verify that all the pointers are consistent. For starters, call it after each insertion to make sure that the list is valid. After all, if the prev pointers are messed up going into copyList, then there's no hope that copyList will ever work.

Once you're sure that insert is working, put a call to validate() at the beginning of copyList(). They put 2 more calls at the end: one to validate the new list and one to revalidate the old one. This will help narrow down any other problems.

The most common problem with doubly linked lists seems to be forgetting to handle the prev pointers. I see that your copyList function doesn't set any prev pointers so that's one problem for sure.
I will close this one.
I have written another one which runs but then it bombs out.
It bombs out before I can test the copyList function and the delete function
Topic archived. No new replies allowed.