Doubly List Copy Constructor: How different is it from a Singly List Copy Constructor?

1.2k Views Asked by At

I just finished working on a singly list copy constructor, and I'm now headed to making a doubly list copy constructor. Can anyone tell me how different it is from a singly list constructor, cause I'm conflicted between starting afresh for my doubly linked list copy constructor or copying my singly list copy constructor. How should I go about this?

If it helps, here is my copy constructor from my singly linked list:

        List(const List &copying) : head(NULL)
        {
            Node* cur = copying.head;
            int size = copying.size();
            Node* end = NULL;
            for(int q = 0; q < size; q++)
            {
                Node* n = new Node;
                n->value = cur->value;
                if (head == NULL)
                {
                    head = n;
                    end = head;
                }
                else
                {
                    end->next = n;
                    end = n;
                }
                cur = cur->next;
            }
            end->next = NULL;
        }

Any and all input is welcome. Thanks everyone :-)

1

There are 1 best solutions below

4
On BEST ANSWER

I think you just have to store the previous node (prv). Assuming Your Node has prv as data member.

List(const List &copying) : head(NULL)
{
    Node* cur = copying.head;
    int size = copying.size();
    Node* end = NULL;
    Node* prv = NULL:
    for(int q = 0; q < size; q++)
    {
        Node* n = new Node;
        n->value = cur->value;
        if (head == NULL)
        {
            head = n;
            end = head;
        }
        else
        {
            end->next = n;
            end = n;
        }
        n->prv=prv;
        prv=n;
        cur = cur->next;
    }
    end->next = NULL;
}