使用链接列表复制堆栈的构造函数

时间:2013-02-12 13:32:06

标签: c++

template <class T>
Stack<T>::Stack(const Stack<T>& otherStack)
{
        List<T> the=otherStack.list;
        ListItem<T> *temp=the.getHead();
        while(temp!=NULL)
        {
                push(temp->value);
                temp=temp->next;
        }
}

我正在使用链表制作堆栈而我的复制构造函数不起作用。请有人帮忙。

List<T>的复制构造函数定义为:

template <class T>
List<T>::List(const List<T>& otherList)
{
    head=NULL;
    ListItem<T> *temp=otherList.head;

    while (temp!=NULL)
    {
        insertAtTail(temp->value);
        temp=temp->next;
    }
}

3 个答案:

答案 0 :(得分:1)

如果ListStack具有通常的语义,则构造函数会反转构造对象中项的顺序。因此,您应该以相反的顺序遍历列表,或者执行此类复制两次以恢复原始顺序。也可以使用赋值运算符和

复制List
this.list = otherStack.list

就够了。但是没有看到我无法分辨的List代码。

答案 1 :(得分:0)

假设listStack的唯一成员(因为它足够了),并且List已经实现了正确的复制构造函数,您当前正在使用第一个复制列表赋值:

template <class T>
Stack<T>::Stack(const Stack<T>& otherStack)
{
        List<T> the=otherStack.list;        // <-- list is copied
        ListItem<T> *temp=the.getHead();
        while(temp!=NULL)
        {
                push(temp->value);
                temp=temp->next;
        }
}

在获取整个列表的副本后,您将该副本的元素推送到堆栈中。但只是将列表复制到成员list(或更好地说:用list的列表初始化otherStack)足以复制整个堆栈:

template <class T>
Stack<T>::Stack(const Stack<T>& otherStack) :
    list (otherStack.list)  // <--- list is copied
{
}

这可能只是将问题“移动”到List的复制结构。

答案 2 :(得分:-1)

代码片段不足以识别问题。 例如,行:

List<T> the=otherStack.list;

制作列表的副本,如果链接列表实现是自定义的,则其复制构造函数可能存在问题。 尝试

List<T> &the=otherStack.list;
相关问题