2017-03-03 47 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,删除的节点应该保存在清单对象的去清除程序中。