链接列表,我的逻辑有缺陷
linked list, where is my logic flawed?
所以我当然已经浏览了很多链接列表的帮助,但除了我似乎无法弄清楚我的问题出现了什么。我想我理解其他代码的逻辑,但是我的某些东西无法正常工作。
功能的代码:
void SparseM_list::newTerm(valueType newValue, int row, int column)
MatrixTerm *n = new MatrixTerm;
n->next = NULL;
n->column = column;
n->row = row;
n->value = newValue;
if (head != NULL)
{
cur = head;
while (cur->next != NULL)
{
cur = cur->next;
cout << "does it ever get inside the while loop? cur and curnext -> " << cur << " " << cur->next << endl; <-- never outputs
}
cur->next = n;
}
else //if head is null, n will be the starting point
{
head = n;
}
delete n;
}
及以下是使用链接列表
的我稀疏矩阵的私有结构/变量struct MatrixTerm {
valueType value; //store value of matrix element
int column; //store column position
int row; //store row position
MatrixTerm *next; //point to next node in the linked list
};
MatrixTerm *head; //head point for the linked list
MatrixTerm *cur, *prev;
基本上我的逻辑是这个
- 新术语信息将动态分配给矩阵项n。
- 如果头为null(默认构造函数设置),则头= n
- 第二组数据进入。头!= null,所以我将CUR指针设置为等于头
- while循环被跳过第二个数据,因为head->下一步应为null,因此cur->下一步应为null。我将cur->设置为下一个等于n
- 第三个数据进入。cur->接下来有n个来自上一个的n,因此它输入了while循环。电流设置为cur->下一步。它检查了wire循环条件,这一次,cur->下一个应该为null,因此将设置cur-> next = n(第3个数据集)。
但是,它永远不会进入时循环。我在哪里弄乱事情?While循环用于穿越链接列表。
此语句
delete n;
没有意义。删除它。
我希望最初的数据成员head
确实设置为NULL
(或nullptr
)。
该功能的替代实现看起来像
void SparseM_list::newTerm(valueType newValue, int row, int column)
{
MatrixTerm *n = new MatrixTerm { newValue, column, row, nullptr };
MatrixTerm **current = &head;
while ( *current ) current = &( *current )->next;
*current = n;
}
如果列表允许附加新节点,则声明另外一个数据成员tail
将很有帮助。在这种情况下
还考虑要删除数据成员cur
和prev
并将其用作方法的局部变量。
您不应该delete n;
,因为它会释放列表节点的内存。您看到,您将钥匙推入锁中,但是在打开门之前,您可以拔出钥匙...您可以进入房屋吗?
ps,删除节点应保存在列表对象的命令器中。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 0-1背包代码中的错误.我的代码中有什么错误
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 为什么兰德每次都给我几乎相同(但略有不同)的数字
- 我的逻辑反转字符串中的元音有什么问题?
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 我的输出中有一个额外的 0,为什么会这样
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- 我的代码中有错误,未声明的标识符
- 我的C++语言蛮力算法有问题
- 如何确定我的处理器有多少个 AVX 寄存器?
- C++无法解决我的问题。我有控制台错误
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 代码在 CodeSignal 中工作不正确。不确定这是否是我的代码缺陷
- 我的堆栈和库存清单程序的结构有什么问题?
- 无法打印完整的二叉搜索树,因为我从最低节点向后迭代的逻辑有缺陷
- 链接列表,我的逻辑有缺陷
- 在C++中,这个Eigen::张量的声明是安全的,还是有缺陷的?我应该为它提交一个问题吗