我无法按数字顺序将结构插入到链表中。每个结构都有一个“数字”,如下面的代码所示。我试图让编号最小的结构成为列表的头部(即:是“人”指向的结构)。我一整天都在盯着这段代码,我无法弄清楚它有什么问题。任何帮助深表感谢。感谢
Person *addPerson(Person *people, Person *addition, int &numList)
{
if (people == NULL && numList == 0)
{
people = addition;
numList++;
return people;
}
if (people->number >= addition->number)
{
addition->nextPerson = people;
people = addition;
return people;
}
else if (people->number < addition->number && people->nextPerson != NULL)
{
addPerson(people->nextPerson, addition, numList);
}
else if (people->number < addition->number && people->nextPerson == NULL)
{
people->nextPerson = addition;
numList++;
return people;
}
}
编辑**
int main()
{
Person *blake = new Person;
Person *kyra = new Person;
Person *elon = new Person;
Person *bill = new Person;
Person *people = NULL;
blake->number = 1;
blake->name = "blake";
blake->lastName = "madden";
blake->nextPerson = NULL;
kyra->number = 2;
kyra->name = "kyra";
kyra->lastName = "madden";
kyra->nextPerson = NULL;
elon->number = 3;
elon->name = "elon";
elon->lastName = "musk";
elon->nextPerson = NULL;
bill->number = 4;
bill->name = "bill";
bill->lastName = "gates";
bill->nextPerson = NULL;
int num = 0;
int &numList = num;
people = addPerson(people, blake, numList);
people = addPerson(people, kyra, numList);
people = addPerson(people, elon, numList);
people = addPerson(people, bill, numList);
cout << people->name << '\n' << people->lastName;
}
答案 0 :(得分:2)
您没有在第三个addPerson()
块中使用if
的返回值。尝试:
people->nextPerson = addPerson(people->nextPerson, addition, numList);
return people;
你还需要return people;
,否则你将失去你的功能的结束而不返回任何合理的东西(我的编译器警告我,你应该改变你的警告设置,所以你的也是如此)。
通过上述更改,您的代码似乎正常运行。
答案 1 :(得分:1)
您永远不会分配返回的头部。它应该是
people->nextPerson = addPerson(people->nextPerson, addition, numList);
答案 2 :(得分:0)
你的问题是函数的参数。您希望在递归调用顺序中修改前一个调用方中节点中的指针,但您只是传递下一个节点的指针值。这不允许您实际修改上一个节点的指针成员。
更改您的功能,使其如下所示:
void addPerson(Person** people, Person *addition, int &numList)
然后当您在第三个区块中调用addPerson
时,请执行以下操作:
addPerson(&(*(people)->nextPerson), addition, numList);
最后,当您访问people
参数时,请确保进行额外的解除引用,例如:
*people = addition;
或
if ((*people)->number >= addition->number)