Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Doubly Linked Lists (copy Constructor And Assignment Operator) (http://www.go4expert.com/forums/doubly-linked-lists-copy-constructor-t8457/)

japji 25Jan2008 02:39

Doubly Linked Lists (copy Constructor And Assignment Operator)
 
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!

shabbir 25Jan2008 08:56

Re: Doubly Linked Lists (copy Constructor And Assignment Operator)
 
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 25Jan2008 09:43

Re: Doubly Linked Lists (copy Constructor And Assignment Operator)
 
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 25Jan2008 20:37

Re: Doubly Linked Lists (copy Constructor And Assignment Operator)
 
Your requirement does not say anything about you are asking and so its about you to judge.


All times are GMT +5.5. The time now is 05:00.