2017-03-03 48 views
-2

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

代碼的功能:

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; 

所以基本上我的邏輯是這樣的

  1. 新術語信息動態分配給矩陣術語n。
  2. 如果頭部爲空(這是由默認構造設置),則頭= N
  3. 第二組數據變爲英寸頭!= NULL,所以設置CUR指針等於頭
  4. 的while循環會跳過第二個數據,因爲head-> next應該爲空,所以cur-> next應該爲空。我設置了cur-> next等於n
  5. 第三個數據進入.Cur-> next從前面有n個,所以它進入while循環。當前設置爲cur-> next。它檢查while循環條件,這次cur-> next應該爲空,所以它設置cur-> next = n(第3個數據集)。

但是,它永遠不會進入while循環。我在哪裏搞砸了? while循環用於遍歷鏈表。

回答

1

本聲明

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。在這種情況下,新節點將被添加到尾部,每次執行循環時效率都會更高。

也想到刪除數據成員curprev並將它們用作方法的局部變量。

+0

你實際上正在分配指針,然後你刪除它,所以每當cur-> next指向NULL – Kochoba

0

你不應該delete n;,因爲它會釋放你的列表節點的內存。你看,你一直把鑰匙插入鎖中,但在打開門之前,你拔出鑰匙......你能進入房子嗎?

ps,刪除的節點應該保存在清單對象的去清除程序中。