Doubly Linked Lists (copy Constructor And Assignment Operator)

japji's Avatar, Join Date: Jan 2008
Newbie Member
Hey Guys,

My first post here...i'm just starting out with C++ and am stuck on a project. any advice will be appreciated...here's the code :

Code:
Bag::Bag(const Bag &aBag): size(aBag.size()) 
{
if(aBag.head == NULL) 
head=NULL; 
else 
{
head = 
new Node; 
assert(head != NULL);
head->value = aBag.head->value;
head->prev = NULL;//////////IS THIS CORREECT???
Node *newptr = head;
for (Node *origPtr = aBag.head->next;origPtr != NULL; origPtr = origPtr->next) 
{
newPtr->next = 
new Node; 
assert(newPtr->next != NULL);
newPtr = newPtr->next;
newPtr->value = origPtr->value;
newPtr->prev = origPtr->prev; //////// IS THIS THE RIGHT WAY???
}
newPtr->next = NULL;
}
}
where.... 
 
struct
Node 
{
ItemType value;
Node *next;
Node *prev;
};
Node *head;
and Bag is obviously the class......i'm trying to make a copy constructor here for the doubly linked list but not sure of exactly how to link the PREV POINTER to the PREVIOUS node when a new node's copied.....can u help me out pls..thanks...

ALSO IF SOME1 COULD OUTLINE AN ASSIGNMENT OPERATOR FOR THE SAME CLASS,I'D BE GREATFUL...THANKS AND TAKE CARE!

Last edited by shabbir; 25Jan2008 at 08:55.. Reason: Code block
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
It depends on what you need to do be doing with the copy constructor but as a general solution you should even be copying the prev and next from the source node.
japji's Avatar, Join Date: Jan 2008
Newbie Member
but isn't that what i'm already doing with newPtr->prev = origPtr->prev...??
i don't knw if it should be that or "newPtr->prev= head;"

As for the copy constructor, this is the requirement we got :

Copy constructor
When a brand new Bag is created as a copy of an existing Bag, enough new nodes must be allocated to hold a duplicate of the original list.


Thanks for the help
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Your requirement does not say anything about you are asking and so its about you to judge.