C++ 链表,我的逻辑哪里有缺陷?
当然,我已经查阅了很多链表帮助,但我似乎无法找出我的链表出了什么问题。我想我理解其他代码的逻辑,但我的代码出了问题,我无法让它正常工作 功能代码:C++ 链表,我的逻辑哪里有缺陷?,c++,list,pointers,linked-list,singly-linked-list,C++,List,Pointers,Linked List,Singly Linked List,当然,我已经查阅了很多链表帮助,但我似乎无法找出我的链表出了什么问题。我想我理解其他代码的逻辑,但我的代码出了问题,我无法让它正常工作 功能代码: void SparseM_list::newTerm(valueType newValue, int row, int column) MatrixTerm *n = new MatrixTerm; n->next = NULL; n->column = column; n->row
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;
}
所以基本上我的逻辑是
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
,并将它们用作方法的局部变量。您不应删除n代码>,因为它将释放列表节点的内存。你看,你一直把钥匙插进锁里,但在开门之前你把钥匙拔出来……你能进房子吗
ps,删除节点应该保存在列表对象的Destructor中。您实际上是在分配指针,然后删除它,因此每次cur->next都将指向NULL
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;
}