【发布时间】:2019-08-09 03:03:30
【问题描述】:
我正在尝试在 C++ 中合并两个链表而没有就位。但是每次创建的新列表在到达一个或另一个列表的 nullptr 后都会发出以下数字。
MyLinkedList mergeTwoLinkedList(MyLinkedList b) {
MyLinkedList c;
node *tempa = this->head;
node *tempb = b.head;
if (b.head == nullptr)
return *this;
if (this->head == nullptr)
return b;
if (tempa && tempb) {
do
{
if ((tempa->val) <= (tempb->val)) {
c.addAtTail(tempa->val);
tempa = tempa->next;
} else if ((tempa->val) >= (tempb->val)) {
c.addAtTail(tempb->val);
tempb = tempb->next;
}
}
while (tempa && tempb);
return c;
}
}
【问题讨论】:
-
不确定这是您的问题,但如果您的程序达到
tempa && tempb并且这是错误的(尽管我认为由于您的其他 if 语句而这可能是不可能的),your program results in undefined behavior。 -
return c;应该移到最后一个}之前 -
But everytime the new list created emits out the following numbers after it reaches the nullptr什么数字? -
在
while (tempa && tempb);之后,您应该查看tempa或tempb是否不为空,并将所有剩余节点添加到c -
玩具代码存在多个问题。除了上面发现的:
addAtTail是如何实现的?如果您添加到列表的实际末尾,则意味着您要添加到tempa或tempb的末尾。