因此,我使用了动态堆栈,我想编写一个复制构造函数,该构造函数必须从同一类的另一个实例复制堆栈的数据。我正在尝试编写该函数,但似乎很难。有人可以帮我吗?
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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
STL容器适配器std::stack具有一项分配operator=,可让您完全做到这一点
#include <stack>
int main()
{
std::stack<int> s1;
std::stack<int> s2;
s1 = s2;
}
Run Code Online (Sandbox Code Playgroud)
如果您需要手动执行此操作,则可以使用@FredOverflow的递归解决方案,也可以使用两个循环和一个临时堆栈来进行操作,可重复使用的版本将其保留在堆栈框架上(双关语意味)。
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);
Run Code Online (Sandbox Code Playgroud)