链接列表,我的逻辑有缺陷

linked list, where is my logic flawed?

本文关键字:有缺陷 我的 列表 链接      更新时间:2023-10-16

所以我当然已经浏览了很多链接列表的帮助,但除了我似乎无法弄清楚我的问题出现了什么。我想我理解其他代码的逻辑,但是我的某些东西无法正常工作。

功能的代码:

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. 如果头为null(默认构造函数设置),则头= n
  3. 第二组数据进入。头!= null,所以我将CUR指针设置为等于头
  4. while循环被跳过第二个数据,因为head->下一步应为null,因此cur->下一步应为null。我将cur->设置为下一个等于n
  5. 第三个数据进入。cur->接下来有n个来自上一个的n,因此它输入了while循环。电流设置为cur->下一步。它检查了wire循环条件,这一次,cur->下一个应该为null,因此将设置cur-> next = n(第3个数据集)。

但是,它永远不会进入时循环。我在哪里弄乱事情?While循环用于穿越链接列表。

此语句

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并将其用作方法的局部变量。

您不应该delete n;,因为它会释放列表节点的内存。您看到,您将钥匙推入锁中,但是在打开门之前,您可以拔出钥匙...您可以进入房屋吗?

ps,删除节点应保存在列表对象的命令器中。