所以我當然也看了很多鏈接列表的幫助和所有,但我似乎無法弄清楚我的錯在哪裏。我想我理解其他代碼的邏輯,但是我的東西已經出現,我無法正常工作。鏈表,我的邏輯瑕疵在哪裏?
代碼的功能:
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