所以我当然也看了很多链接列表的帮助和所有,但我似乎无法弄清楚我的错在哪里。我想我理解其他代码的逻辑,但是我的东西已经出现,我无法正常工作。链表,我的逻辑瑕疵在哪里?
代码的功能:
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。
- 如果头部为空(这是由默认构造设置),则头= N
- 第二组数据变为英寸头!= NULL,所以设置CUR指针等于头
- 的while循环会跳过第二个数据,因为head-> next应该为空,所以cur-> next应该为空。我设置了cur-> next等于n
- 第三个数据进入.Cur-> next从前面有n个,所以它进入while循环。当前设置为cur-> next。它检查while循环条件,这次cur-> next应该为空,所以它设置cur-> next = n(第3个数据集)。
但是,它永远不会进入while循环。我在哪里搞砸了? while循环用于遍历链表。
你实际上正在分配指针,然后你删除它,所以每当cur-> next指向NULL – Kochoba