复制双向链表的构造函数

时间:2013-02-09 15:50:43

标签: c++

我在制作复制构造函数时遇到问题。 请考虑以下代码:

在List.h中

template <class T>
struct ListNode
{
    T value;
    ListNode<T> *next;
    ListNode<T> *prev;

    ListNode(T theVal)
    {
        this->value = theVal;
        this->next = NULL;
        this->prev = NULL;
    }
};

template <class T>
class List
{
    ListNode<T> *head;

public:
    List();
    List(const List<T>& otherList); // Copy Constructor.
    ~List();
    };

在list.cpp中

template <class T>
List<T>::List()
{
    head=NULL;
}
template <class T>
List<T>::~List()
{
}
template <class T>
List<T>::List(const List<T>& otherList)
{
}

//我有谷歌问题。概念很简单。创建一个新头并为其节点分配旧List节点的值。 //所以我尝试了以下内容。

ListNode<T> *old = head; // pointer to old list.
ListNode<T> *new;// pointer to new head.

while (old->next!=NULL){
new->value = old->value;
old = old->next; 
}

//唯一的问题是如何创建一个指向我的新复制列表的新头。

1 个答案:

答案 0 :(得分:1)

整个问题尚不清楚,代码存在许多问题,包括无用的析构函数,而不是复制赋值运算符。

您通常无法在.cpp文件中定义模板,整个模板定义必须对代码的所有用户可见,这通常意味着在头文件中定义整个模板。

ListNode<T> *new;// pointer to new head.

new是C ++中的关键字,您不能将其用于变量名称。

  

//唯一的问题是如何创建一个指向我的新复制列表的新头。

什么是复制清单?您实际上没有复制任何内容或创建任何新节点。

您需要在otherList

中创建节点的副本
template <class T>
List<T>::List(const List<T>& otherList)
{
  ListNode<T>* node = otherList.head;
  ListNode<T>** tail = &head;
  while (node)
  {
    *tail = new ListNode<T>(node->value);
    tail = &tail->next;
    node = node->next;
  }
}
相关问题