使用递归的二维链表复制构造函数
2-d Linked List copy constructor using recursion
我正在尝试制作一个二维单向链表,其中每个节点都有一个右指针和一个下面的指针。 我在实现复制构造函数时遇到了很多麻烦,因为我很确定递归是要走的路,而且我在递归方面很糟糕。 我是否需要更改您看到的任何内容,或者它看起来正常?
下面是标头中的声明:
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.
}
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 将二维矢量传递给类
- 链表,反向函数,数据结构
- 将值从二维数组输出到文本文件
- 使用std::list创建循环链表
- 我在二维向量中是否正确分配了内存
- 将二叉树的节点插入链表 (C++)
- ASAN:将二叉树平展为链表时释放后堆使用
- 为什么我的二维表不正确显示
- 使用递归的二维链表复制构造函数
- 我的二维码阅读器应用无法打开链接
- 给定一个二叉树,设计一个算法,创建每个深度的所有节点的链表
- 转换二叉搜索树到链表
- 当条目以有序的方式添加时,二叉搜索树有效地充当链表
- 在c++中创建一个二维链表对象
- 如何编写一个程序,从键盘上填充一个二维整数表a[3][2]
- 链表中的链表(二维链表?