【发布时间】:2021-05-04 06:29:15
【问题描述】:
我想从链接列表中删除所有重复项。我知道 GeeksForGeeks 上有一个与我的非常相似的确切程序,我可以使用它,但我想了解为什么我的程序不起作用。
代码:
class Node {
public:
int data;
Node *next;
};
void removeDuplicatesAlpha(Node* start)
{
Node* ptr1 = start;
Node* ptr2 = NULL;
Node* dup = NULL;
int i = 0;
/* Pick elements one by one */
while (ptr1 != NULL && ptr1->next != NULL)
{
ptr2 = ptr1->next;
//0 1 2 3 4
/* Compare the picked element with rest
of the elements */
while (ptr2 != NULL && ptr2->next != NULL)
{
cout << i;
i++;
/* If duplicate then delete it */
if (ptr1->data == ptr2->data)
{
/* sequence of steps is important here */
dup = ptr2;
ptr2 = ptr2->next;
delete(dup);
}
else /* This is tricky */
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
}
int main()
{
Node* head = NULL;
push(&head, 3);
push(&head, 3);
push(&head, 20);
push(&head, 14);
push(&head, 9);
push(&head, 20);
push(&head, 20);
printList(head);
//removeDuplicates(head);
removeDuplicatesAlpha(head);
printList(head);
deleteList(&head);
return 0;
}
我最后打印的是 4。
这是错误:抛出异常:读取访问冲突。 ptr2 为 0xDDDDDDDD。
如果这是一个愚蠢的问题,我很抱歉,但我刚刚开始使用 C++ 中的数据结构。
【问题讨论】:
-
请提取并提供minimal reproducible example。对于此类程序,如果您使用调试器逐步完成它或创建数据结构图,也会有所帮助。作为这里的新用户,也可以使用tour 并阅读How to Ask。
-
0xDDDDDDDD你的调试器正试图告诉你一些事情。相关:https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations0xDDDDDDDD表示已释放堆内存。
标签: c++ pointers data-structures