Home > Software design >  Create a copy constructor that reverses a stack using a linked list stack implementation
Create a copy constructor that reverses a stack using a linked list stack implementation

Time:04-28

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.

CodePudding user response:

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.

CodePudding user response:

A pragmatic approach could be to just copy the data twice:

linkList(linkList const& rhs) {
    linkList tmp;
    // first copy to `tmp`, which will have them in reverse:
    for(Node* curr = rhs.top; curr; curr = curr->down) 
        tmp.push(curr->letter);

    // then populate *this from `tmp` which will then have them
    // in the original order:
    for(Node* curr = tmp.top; curr; curr = curr->down)
        push(curr->letter);
}
  • Related