所以我一直在做一个关于数据结构的家庭作业,几个多小时以来,我陷入了死胡同。为了解释,我必须在文本文件ListJava和ListDS中获取以下格式的信息:姓名、姓氏、NUM grade。这两个文件包含相同的名称,但顺序不同。这个任务基本上是想让我们对文件进行合并排序。
以下是我的结构:
typedef struct student
{
string name;
string surname;
int am;
int grade;
}StudentFile;
typedef struct node {
StudentFile element;
struct node* next;
}Node;
typedef struct stud
{
string name;
string surname;
int am;
int grade;
int grade2;
struct stud* next;
}Student;下面是我的合并它们的函数:
/*Merge Lists into one*/
Student* MergeLists(Node* headDS, Node* headJava, Student* head)
{
bool flag = false;
Student *a = new Student;
Student *prev = NULL;
Student *temp = NULL;
Node *tempDS = headDS;
Node *tempJava = headJava;
Node *prevJava = NULL;
if (head == NULL)
{
head = a; //mermory alocation for head<Student>
temp = head;
// temp->next = NULL;
}
while (tempDS != NULL)
{
if(head != NULL)
{
if (tempDS->element.surname.compare(tempJava->element.surname) == 0) // if surnames are equal
{
prev = temp;
temp->name = tempDS->element.name;
temp->surname = tempDS->element.surname;
temp->am = tempDS->element.am;
temp->grade = tempDS->element.grade;
temp->grade2 = tempJava->element.grade;
tempJava = tempJava->next;
tempDS = tempDS->next;
temp = temp->next;
flag = false; //meaning that prevJava can get a new value again.
}
else // if DS > Java
{
/*Keep tempJava in mermory while iterating through the next nodes to find the temp that is equal to DS*/
if (flag == false)
{
prevJava = tempJava;
tempJava = tempJava->next;
flag = true;
}
else
{
tempJava = tempJava->next;
}
}
/*temp = temp->next;
tempJava = tempJava->next;
tempDS = tempDS->next;*/
}
prev->next = a;
}
a->next = NULL;
return a;
}问题出在temp =temp->下一行。尽管第一次运行是完全正常的,然后正确地搜索ListJava以找到与ListDS相同的名称,但临时值是0xcdcdcdcd {...},并抛出了一个异常:
Exception thrown at 0x00C38EF0 in Exercise3_zitima2.exe: 0xC0000005: Access violation reading location 0xCDCDCDE5.我怎么才能纠正这个错误,我真的到处都在尝试,但似乎什么都没有解决。我知道这不是一个要求别人来解决我的任务的地方,当然,只是需要一点指导。
发布于 2015-11-12 10:05:53
您的Student结构没有构造函数,所以当您分配一个构造函数并将其分配给MergeLists中的a时,a->next将包含垃圾。( 0xCDCDCDCD是MSVC填充已分配内存的地方,因此您可以看到这些未初始化的使用情况。)
您需要让构造函数将next指针设置为NULL,或者在分配指针后将其手动设置为NULL。
发布于 2015-11-12 15:14:43
合并列表功能通常用于合并两个已排序的列表。不涉及节点分配。将来自一个列表的第一个节点与另一个列表的第一个节点进行比较。较小的节点从它的列表中删除,并附加到最初为空的列表中,该列表将以合并后的节点结束。唯一更改的节点成员是下一个指针。重复该过程,直到到达一个列表的末尾,然后将添加到合并列表的最后一个节点的下一个指针设置为指向另一个列表的剩余部分的第一个节点,并且完成合并。
https://stackoverflow.com/questions/33663176
复制相似问题