Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a copy constructor that reverses a stack using a linked list stack implementation

linkList::linkList(linkList const& rhs){
    Node *temp = rhs.top;
    Node *temp_stack = rhs.top;
    while(temp){
        char value = temp->letter;
//        push(value);
        push(temp_stack->letter);
        temp = temp_stack->down;
        temp_stack = temp_stack->down;
//        temp = temp->down;
    }
}

void linkList::push(char c) {
    Node* new_top = new Node(c);
    new_top->down = top;
    top = new_top;
}

I have a problem on my copy constructor that when I call it it, it display the link-list in reverse which make sense cause I am pushing it to the back of the new link-list. assuming that my function is working 100 percent and I cant change the function. how would I go about adding it in reverse?
I looked over couple solution in here but no pretty helpful.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For starters declarations of these two pointers within the function

    Node *temp = rhs.top;
    Node *temp_stack = rhs.top;

does not make a great sense. They duplicate each other. It is enough to use one pointer to traverse the list rhs.

If you want to create a copy of the passed list then the function push is not suitable.

You could define the copy constructor the following way.

linkList::linkList( linkList const& rhs ) : top( nullptr )
{
    Node **current = ⊤

    for ( Node *temp = rhs.top; temp != nullptr; temp = temp->down )
    {
        *current = new Node( temp->letter );
        current = &( *current )->down;
    } 
}

I hope that the constructor of the class Node sets the data member down of the created node to nullptr.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading