复制双向链表的构造函数 [英] Copy constructor for a doubly linked list

查看:1179
本文介绍了复制双向链表的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在制作副本构造函数时遇到问题。
考虑下面的代码:

I am having problems making a copy constructor. Consider the code below:

在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)
{
}

//我有google的问题。概念很简单。创建一个新的头并为其节点分配旧的List节点的值。
//因此,我已经尝试过以下操作。

// I have google the problem. Concept is simple. Make a new head and assign its node the //values of old List node. // So for I have tried the following.

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; 
}

//唯一的问题是如何创建一个新的head,我的新复制列表。

// The only problem is how to make a new head that would point to my new Copied list.

推荐答案

这个整个问题不清楚,并且有一些问题的代码,析构函数和非复制赋值运算符。

This whole question is unclear, and there are a number of problems with the code, including a useless destructor, and not copy assignment operator.

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

You can't generally define templates in a .cpp file, the entire template definition must be visible to all users of the code, which generally means defining the entire template in header files.

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

new 是C ++中的关键字不能用它作为变量名。

new is a keyword in C++, you can't use it for variable names.


//唯一的问题是如何创建一个新的head,列表。

// The only problem is how to make a new head that would point to my new Copied list.

复制的列表?您尚未实际复制任何内容或创建任何新节点。

What copied list? You haven't actually copied anything or created any new nodes.

您需要在 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;
  }
}

这篇关于复制双向链表的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆