Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a stack?

Tags:

c++

So I use a dynamic stack and I want to write a copy constructor, which has to copy the stack's data from another instance of the same class. I'm trying to write the function, but it seems pretty hard. Could somebody give me a hand?

template<typename T=int>
class LStack
{
public:

    template<typename U=int>
    struct elem
    {
        U con;
        elem<U>* link;
    }

private:

    elem<T>* el;

    void Copystack(Lstack const& stack)    // HERE
    {
        elem<T>* last = el;
        el->con = stack->con;
        while(stack->link != null)
        {
            var temp = new elem<T>;
            temp->con = stack->con;
            temp->link = stack->link;
            stack = stack->link;
        }
    }

};
like image 440
Ivan Prodanov Avatar asked Feb 18 '23 14:02

Ivan Prodanov


1 Answers

The STL container adaptor std::stack has an assignment operator= that allows you to do exactly that

#include <stack>

int main()
{
   std::stack<int> s1;
   std::stack<int> s2;
   s1 = s2;
}

If you need to do it manually, you can use @FredOverflow's recursive solution, or you could do it with two loops and a temporary Stack, which the recurisve version keeps on the stack frame (pun intended).

void copy_reverse(Stack& source, Stack& dest)
{
    while(!source.empty())
        dest.push(Element(source.top()));
        source.pop();
    }
}

Stack src, tmp, dst;
copy_reverse(src, tmp);
copy_reverse(tmp, dst);
like image 140
TemplateRex Avatar answered Feb 26 '23 21:02

TemplateRex