Doubly Linked Lists (copy Constructor And Assignment Operator)

Discussion in 'C++' started by japji, Jan 24, 2008.

  1. japji

    japji New Member

    Joined:
    Jan 24, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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 a moderator: Jan 25, 2008
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    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.
     
  3. japji

    japji New Member

    Joined:
    Jan 24, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Your requirement does not say anything about you are asking and so its about you to judge.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice