C++ 链表访问冲突写入位置
我正在写一个程序,用SSN进行LSD基数排序。程序将把数字解析成3位数字,并进行3次传递。每次通过时,我将数字存储到相应的数组元素bucket[];如果有重复项,我会在该位置创建一个链表,并将重复项存储在已经存在的链表后面。当我尝试在链表的末尾插入时,代码中断 编辑新的错误消息C++ 链表访问冲突写入位置,c++,pointers,linked-list,C++,Pointers,Linked List,我正在写一个程序,用SSN进行LSD基数排序。程序将把数字解析成3位数字,并进行3次传递。每次通过时,我将数字存储到相应的数组元素bucket[];如果有重复项,我会在该位置创建一个链表,并将重复项存储在已经存在的链表后面。当我尝试在链表的末尾插入时,代码中断 编辑新的错误消息 class node { public: node(int n, node *p){data=n;next=p;} int data; node *next; }; void genData
class node
{
public:
node(int n, node *p){data=n;next=p;}
int data;
node *next;
};
void genData(int *dta, int n)
{
for(int i=0; i < n; i++)// generate the social security numbers at random
dta[i] = rand()%889 + 111 + 1000*(rand()%889 + 111) + 1000000* (rand()%889 + 111);
}
int radixSort(int *dta, int n, int *out)
{
// the dta array contains the data to be sorted.
// n is the number of data items in the array
// out is the array to put the sorted data
node *bucket[1000]; // declare an array of 1000 linked lists (head pointers)
int count = 0; // use this to count the instructions to graph the big-o
for(int i = 0; i < n; i++)out[i] = dta[i];
for (int pass = 0; pass < 3; pass++)
{
for (int j = 0; j < 1000; j++){
bucket[j] = NULL;
}
delete bucket;
delete[]bucket;
for (int i = 0; i < n; i++){
int index=0;
switch (pass)
{
case 0:
index = out[i] % 1000;
case 1:
index = (out[i]/1000) % 1000;
case 2:
index = out[i] / 1000000;
};
if (bucket[index] = NULL){
bucket[index] = new node(out[i], NULL);
}
else{
node *cur=bucket[index];
while (cur->next!= nullptr){ //****access violation reading location
cur = cur->next;
}
node *ptr = new node(out[i], NULL);
cur->next = ptr;
}
}
int idx = 0;
for (int i = 0; i < 1000; i++){
if (bucket[i] == NULL) continue;
else{
out[idx] = bucket[i]->data;
idx++;
count++;
}
}
}
类节点
{
公众:
node(int n,node*p){data=n;next=p;}
int数据;
节点*下一步;
};
void genData(int*dta,int n)
{
for(int i=0;inext!=nullptr){//****访问冲突读取位置
cur=cur->next;
}
node*ptr=新节点(out[i],空);
cur->next=ptr;
}
}
int-idx=0;
对于(int i=0;i<1000;i++){
如果(bucket[i]==NULL)继续;
否则{
out[idx]=bucket[i]>数据;
idx++;
计数++;
}
}
}
您的代码中存在许多问题:
index==out[i]%1000;
这些行进行比较,我怀疑这是您想要的。赋值使用单个=没有检查其中是否已经有指针-这将在第一次通过后导致内存泄漏。请记住:每个新
都需要删除
while(cur!=NULL){cur=cur->next;}
一旦cur是nullptr就退出while循环-这意味着在两行之后尝试去引用它是试图去引用nullptr,这是一个坏主意。为了得到最后一个元素,您可能需要检查的是`while(cur->->next!=nullptr)注意:如果您的编译器支持
nullptr
使用它是一个好主意,即使您可能需要通过适当的标志启用C++11。cur
在while(cur!=null)
之后为null,而我正在使用while(cur->next!=nullptr)
之前,但它给了我一个访问冲突读取位置错误您的下一个
是否在节点
构造函数中正确初始化?是类节点{int data;节点*next;节点(int n,节点*p){data=n;next=p;}
您是否将其与其他更正一起使用?因为如果我看不到实际的代码,我只能推测当时可能还有什么错误。.在上面发布的代码中,您肯定是在取消对nullptryes的引用,我已对其进行了修复。我刚刚发布了编辑后的版本。您能看一看吗?似乎删除
是错误的同时,也会增加一个断点。