Original Post
I am having trouble figuring out how to implement a copy constructor for a doubly circular linked list. I am writing this implementation as a personal exercise from a book I am reading. I am pretty confused on what I should be doing so I'll show what I am and doing and let any who wishes comment on it. Struct for the DoublyListNode are: Thanks for any help.
DoublyList::DoublyList(const DoublyList& aList)
{
size = aList.size;
if(aList.size == 0) // empyt list
{
// dummy points to itself
dummyHead = new DoublyListNode;
dummyHead->next = dummyHead;
dummyHead->precede = dummyHead;
// make sure the listHead points to dummy
listHead = new DoublyListNode;
listHead->next = dummyHead;
listHead->precede = NULL; // not needed just null it
}
else
{
dummyHead = new DoublyListNode;
listHead = new DoublyListNode;
listHead->next = dummyHead;
listHead->precede = NULL;
// start getting a little lost here
// grab head node
DoublyListNode *newPtr = dummyHead;
dummyHead->next = newPtr; // initially dummyHead->next should point to itself
dummyHead->precede = newPtr; // initially dummyHead->precede should point to itself
// travers through copy list from front to back
for(DoublyListNode *origPtr = aList.dummyHead->next; origPtr != aList.dummyHead; origPtr = origPtr->next)
{
// allocate new memory for node copying
newPtr->next = new DoublyListNode;
newPtr->precede = newPtr; // precede points to previous node, which will be newPtr
// having most trouble figuring out what to do with dummyHead if anything
//
// what should happen to dummyHead at this point?
// anything or is this ok?
//
newPtr = newPtr->next; // make newPtr the current ptr
newPtr->item = origPtr->item; // assign the value of copy list into newPtr value
}
// I believe after the loop is done this is correct but unsure
newPtr->next = dummyHead;
}
}
struct DoublyListNode
{
ListItemType item;
DoublyListNode *next;
DoublyListNode *precede;
};
DoublyListNode *listHead;
DoublyListNode *dummyHead;
int size;