链表深拷贝构造函数 [英] Linked list deep copy constructor

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

问题描述

我正在实现一个链表类的副本构造函数,该副本构造函数将进行深层复制。这是我拥有的代码:

I am implementing a linked list class' copy constructor which will make a deep copy. This is the code that i have:

List( const List & rhs ) {
        Node* rhsFront = rhs.header->next;
        Node* prev = header;
        while (rhsFront) {
            prev->next = new Node(rhsFront->data, nullptr);
            rhsFront = rhsFront->next;
            prev = prev->next;
        }
}

但是,它在此行崩溃:

prev->next = new Node(rhsFront->data, nullptr);

我做错了什么?

推荐答案

Node* prev = header;

我猜那里的头文件没有初始化,因此导致prev-> next是a随机指针(很可能是0),试图写入该点会使程序崩溃。如果是这样,这可能行得通。

I would guess the header there not to be initialised, thus causing the prev->next to be a random pointer (most likely something like 0) and trying to write to that point crashes the program. If so, this might work.

List( const List & rhs ) {
    Node* rhsFront = rhs.header->next;
    header = new Node(rhs.header->data, nullptr);
    Node* prev = header;
    while (rhsFront) {
        prev->next = new Node(rhsFront->data, nullptr);
        rhsFront = rhsFront->next;
        prev = prev->next;
    }
}

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

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