删除与另一个成员相等的链表成员的嵌套循环中断.将问题隔离到一行
Nested loop to delete linked list members that are equal to another member is breaking. Isolated the issue to one line
我一直在导师的帮助下做我的链表实验室,但不幸的是,前一段时间我与他们失去了联系,我自己还没能弄清楚这个问题。
我的第一个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
的前身,而是指向您想要找到重复的某个节点的指针。
要修复这个错误,首先为变量使用有意义的名称。cursorOne
和cursorTwo
根本没有意义,它们的名字很可能是你错误的根源。为什么不叫它们nodeToFindDuplicatesOf
和currentItem
呢?(或者你可以想出更好的办法。)
那么你需要引入一个新的指针来跟踪currentItem
的前身。
当需要删除currentItem
时,先设置其前身的link_field
,然后设置delete currentItem
(事先不设置为NULL
)
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- C++多线程程序:变量定义为类成员的隔离错误
- 尝试访问标头声明成员时出现隔离错误
- 调用成员>函数(this);在析构函数中导致隔离错误
- 使用向量<向量>成员实例化对象时的隔离错误<int>
- 推送到成员向量时的隔离错误
- 隔离类的并发/非并发访问数据成员
- 删除与另一个成员相等的链表成员的嵌套循环中断.将问题隔离到一行