2017-08-24 55 views
0

最近,我一直在练习一些链接列表编码问题。我刚开始使用unordered_set。问题是,“编写代码以从未排序的链接列表中删除重复项”。我为此使用了unordered_set。但是当我尝试初始化链表时,我遇到了“coredump”的问题。在“CodePad”(这是一个在线C++编译器)中执行链表操作时的核心转储

当我注释掉populateList的最后3行时,它显示数组。当我尝试访问populateList中的头时,它显示核心转储。

这是我写的全部代码。我已经写在键盘网站上。

#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<<"\n\n"; 
    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<<"\n\n"; 
    while(ptr!=NULL) 
    { 
     cout<<ptr->data<<" "; 
    } 
    return 0; 
} 
+1

有一个可疑的缺乏该代码中的“新”。 – molbdnilo

+1

你可以调用'populateList(head)',其中'head == NULL',然后继续前进,并用'head-> data = ...'取消引用这个'NULL'指针;' –

+0

将以前的注释内容放入其他字:你没有使用operator new来分配列表的节点。 – Fureeish

回答

0

的问题是,在你的for循环设置旁边null,则试图取消对它的引用上下一iteratation

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]; 
... 
相关问题