有3个链接列表,其中2个已按顺序排列。 2个链表被分类到第3个(headZ
)。如果我将headZ
作为指针传递给它,它就会恢复到函数出口处的空列表。如果我通过引用传递,则退出并且headZ
仅包含1个数字。我无法弄清楚如何让它发挥作用。
void SortedRecur(Node*& headX, Node*& headY, Node* headZ){
if (headX == NULL && headY == NULL)
return;
else if (headX == NULL && headY != NULL)
{
if (headZ == 0)
{
headZ = headY;
headY = headY->link;
headZ->link = NULL;
}
else
{
headZ->link = headY;
headY = headY->link;
headZ = headZ->link;
headZ->link = NULL;
}
SortedRecur(headX, headY, headZ);
}
else if (headX != NULL && headY == NULL)
{
if (headZ == 0)
{
headZ = headX;
headX = headX->link;
headZ->link = NULL;
}
else
{
headZ->link = headX;
headX = headX->link;
headZ = headZ->link;
headZ->link = NULL;
}
SortedRecur(headX, headY, headZ);
}
if (headX != NULL && headY != NULL)
{
if (headX->data > headY->data)
{
if (headZ == NULL)
{
headZ = headY;
headY = headY->link;
headZ->link = NULL;
}
else
{
headZ->link = headY;
headY = headY->link;
headZ = headZ->link;
headZ->link = NULL;
}
}
else
{
if (headZ == NULL)
{
headZ = headX;
headX = headX->link;
headZ->link = NULL;
}
else
{
headZ->link = headX;
headX = headX->link;
headZ = headZ->link;
headZ->link = NULL;
}
}
SortedRecur(headX, headY, headZ);
}
cout << "ListZ: "; ShowAll(cout, headZ);} //Test contents of headZ
答案 0 :(得分:0)
如果你没有传递headZ作为参考,那么当传递给这个函数时,headZ指针不会被改变。例如,如果您执行以下操作:
Node* resultHead = NULL;
Node* inputA = GetInitialAList(); // (hypothetical function to get the inital value)
Node* inputB = GetInitialBList();
SortedRecur(inputA, inputB, resultHead);
然后resultHead的值将保持不变,因此它仍然是NULL。
另一方面,如果您更改SortedRecur以将headZ作为引用,则headZ的最终值将指向列表中的最后一个元素,因为每次添加新元素时,您都会headZ = headZ->link;
- 并且所以headZ总是指向列表的末尾。列表的开头就丢失了。
我认为解决问题的最简单方法是保留当前SortedRecur
的实现,但不是为headZ传递NULL指针,而是使用指向实际节点的初始值。这样,SortedRecur可以将排序列表添加到headZ的末尾,并且初始headZ指针不变也无关紧要。例如,这是一种克服方式:
Node dummyNode;
dummyNode.link = NULL;
Node* resultHead = &dummyNode;
Node* inputA = GetInitialAList(); // (hypothetical function to get the inital value)
Node* inputB = GetInitialBList();
SortedRecur(inputA, inputB, resultHead);
// At this point, the value of resultHead is unchanged,
// but the dummyNode now points to the sorted list.
// All we have to do now is discard the dummyNode.
resultHead = dummyNode.link;