删除与另一个成员相等的链表成员的嵌套循环中断.将问题隔离到一行

Nested loop to delete linked list members that are equal to another member is breaking. Isolated the issue to one line

本文关键字:成员 隔离 一行 问题 中断 另一个 链表 删除 嵌套循环      更新时间:2023-10-16

我一直在导师的帮助下做我的链表实验室,但不幸的是,前一段时间我与他们失去了联系,我自己还没能弄清楚这个问题。

我的第一个while循环一次一个节点地遍历链表,然后继续进行第二个while循环,该循环遍历第二个节点并将其与第一个进行比较。这似乎工作得很好。但问题是,当它删除一个成员时,它实际上删除了两个成员。它删除它之前的节点,以及它应该删除的节点。

我将问题隔离到list.cpp的第80行(如下)。我认为cursorOne的link_field指向游标2的链接字段正在删除两个游标之间的所有节点,这不是我想要的。

所以我想我应该有光标1的链接字段指向光标1的下一个链接字段?我感觉如此接近…这个实验最难的部分已经完成了,但我还没有得到最后一个尤里卡时刻,但我一直在看它。

程序如下:它应该是不言自明的。它使用节点类,然后用列表类对其进行变异。

仔细想想,我想我不能链接到ideone.com上的代码。所以我会尽量让它尽可能简短,然后发布这个循环。下面是节点和列表。cpp

      while(currentItem != NULL)
    {
        cout << "Enter Second Loop" << endl;
        cout << currentItem->data_field << " Curse 2" << endl;
        //compare it
        if (nodeToFindDuplicatesOf->data_field == currentItem->data_field)
        {
         //prev->next = current->next to delete
            // in order to delete only one, I must find a way to set the link_field of the previous node to cursor 1 to
            // the link field of the node that's to be deleted
            cout << nodeToFindDuplicatesOf->data_field << "being removed" << endl;
            predecessor = currentItem->link_field;
            delete currentItem;
            currentItem = nodeToFindDuplicatesOf; //set cursor2 to cursor1
        }
        currentItem = currentItem->link_field;
    }
    nodeToFindDuplicatesOf = nodeToFindDuplicatesOf->link_field;
    if (nodeToFindDuplicatesOf)
        currentItem = nodeToFindDuplicatesOf->link_field;
}

}

我需要一个以前的节点指针在我的节点类?

您定位错误的分析是正确的。要从列表中删除一个项目,你需要一个指针,既指向你想要删除的currentItem(又名cursorTwo),也指向它的前身。然而,您的cursorOne指针是而不是 cursorTwo的前身,而是指向您想要找到重复的某个节点的指针。

要修复这个错误,首先为变量使用有意义的名称。cursorOnecursorTwo根本没有意义,它们的名字很可能是你错误的根源。为什么不叫它们nodeToFindDuplicatesOfcurrentItem呢?(或者你可以想出更好的办法。)

那么你需要引入一个新的指针来跟踪currentItem的前身。

当需要删除currentItem时,先设置其前身的link_field,然后设置delete currentItem(事先不设置为NULL)