在 "CodePad" 中执行链表操作时转储的核心(这是一个在线C++编译器)

Core dumped while performing linked list operation in "CodePad" (which is an online C++ compiler)

本文关键字:一个 编译器 C++ 在线 核心 执行 CodePad 链表 操作 转储      更新时间:2023-10-16

最近我一直在练习一些链表编码问题。我刚开始使用unordered_set。问题是,"编写代码以从未排序的链表中删除重复项"。我为此使用了unordered_set。但是当我尝试初始化链表时,我遇到了"核心转储"的问题。

当我注释掉填充列表的最后 3 行时,它会显示数组。当我尝试在填充列表中访问头部时,它会显示核心转储。

这是我编写的整个代码。我已经在代码板网站上写了这个。

#include <iostream>
#include<vector>
#include<string.h>
#include<math.h>
#include<sstream>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<unordered_set>
using namespace std;
struct Node
{
int data;
Node *next;
};
Node *head=NULL;
void populateList(Node *head)
{
int arr[]={7,1,2,3,4,5,4,3,5,7,3,9,3,7,3,6,2,5,7,4};
cout<<"nn";
int n=sizeof(arr)/sizeof(int);
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
Node *ptr=head;

如果我注释掉下面 for 循环中的内容,一切都运行顺利。

for(int i=0;i<n;i++)
{
ptr->data=arr[i];
ptr->next=NULL;
ptr=ptr->next;
}
}
int main()
{
Node *ptr=head, *prev=head;
populateList(head);
unordered_set<int> A;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
}
while(ptr!=NULL)
{
if(A.find(ptr->data)==A.end())
{
A.insert(ptr->data);
}
else
{
prev->next=ptr->next;    
delete ptr;
ptr=prev->next;
}
prev=ptr;
ptr=ptr->next;
}
ptr=head;
cout<<"nn";
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
}
return 0;
}

问题是在你的 for 循环中,你在 NULL 旁边设置,然后尝试在下一次迭代时取消引用它

for(int i=0;i<n;i++)
{
ptr->data=arr[i];
ptr->next=NULL; // now ptr->next is NULL
ptr=ptr->next; // ptr = ptr->next = NULL;
}

如果你展开这个

int i = 0;
ptr->data=arr[0];
ptr->next=NULL;
ptr=ptr->next; // ptr = ptr->next = NULL;
i++;
// because we set ptr to NULL this is dereferencing the NULL pointer
ptr->data=array[1];
...
相关文章: