使用递归的二维链表复制构造函数

2-d Linked List copy constructor using recursion

本文关键字:二维 链表 复制 构造函数 递归      更新时间:2023-10-16

我正在尝试制作一个二维单向链表,其中每个节点都有一个右指针和一个下面的指针。 我在实现复制构造函数时遇到了很多麻烦,因为我很确定递归是要走的路,而且我在递归方面很糟糕。 我是否需要更改您看到的任何内容,或者它看起来正常?

下面是标头中的声明:

typedef int elementType;
struct node;
typedef node* nodePtr;
struct node
{
    elementType elt;
    nodePtr right = NULL;
    nodePtr below = NULL;
};
class LinkedList
{
protected:
    nodePtr head, tail;
    int size;
public:
    LinkedList();
    LinkedList(const LinkedList &list); // copy constructor
    void recursiveCreate(nodePtr ptr);
}

这是我的 cpp 文件中

LinkedList::LinkedList(const LinkedList &list)
{
    nodePtr current = NULL;
    if (list.head == 0)
        head == 0;
    else
    {
        current = list.head;
        recursiveCreate(current);       
    }
}
void LinkedList::recursiveCreate(nodePtr ptr)
{
    nodePtr n = new node; //create new node
    n->elt = ptr->elt;      //copy value into that new node
    n->right = ptr->right;  //move right n pointer
    n->below = n->below;    //move right below pointer
    recursiveCreate(ptr->right);  //call on right node
    recursiveCreate(ptr->below);  //call on below node
}

前面的大事:这是一个二叉树,而不是一个链表。称其为链表只会导致混淆。

在主题上,递归不是链表的方法。对于一棵树来说,它可能是。但是由于几个原因,您拥有的东西不起作用。

1( 没有终止条件。递归将犁入 NULL 指针并做坏事。首先,recursiveCreate如果 nodePtr 为 NULL,则要退出。

2(您正在将当前节点设置为指向错误的内容。例如

n->right = ptr->right;
节点

指向错误列表中的节点。这几乎是一个糟糕的结局。您希望指向由 recursiveCreate 创建的节点。

让我们看一下它必须是什么样子:

nodePtr LinkedList::recursiveCreate(nodePtr ptr)
{
    if (ptr == nullptr) 
    {
        return nullptr; // source tree stops here
    }
    nodePtr n = new node; //create new node
    n->elt = ptr->elt;      //copy value into that new node
    n->right = recursiveCreate(ptr->right);  //call on right node
    n->below = recursiveCreate(ptr->below);  //call on below node
    return n;
}

LinkedList::LinkedList(const LinkedList &list)
{
    nodePtr current = nullptr;
    if (list.head == nullptr) // NAG!!! For Crom's sake! 0 is not a pointer!
        head == nullptr;      // Use nullptr and get type checking working for you.
    else
    {
        head = recursiveCreate(list.head);       
    }
}

特殊奖金运营商

LinkedList & operator=(LinkedList list) // pass by reference. Copy constructor copies 
                                        // for you
{
    std::swap(head, list.head); // steal head from copy and give copy the empty   
    return *this; // all done.
}