我编写了一个合并2个已排序链接列表的函数。但在我知道我提出的逻辑是否正确之前,我在调用函数时遇到了无限循环。我不确定为什么会这样。以下是代码:
ListNode *merge_sorted_list(ListNode *head1, ListNode *head2) {
cout<<"hi\n";
ListNode *curr = new ListNode(-1);
ListNode *start = curr;
cout<<"hi\n";
while(head1 || head2) {
if(head1->val == head2->val) {
curr->next = head1;
curr = curr->next;
curr->next = head2;
if(head1) head1 = head1->next;
if(head2) head2 = head2->next;
} else if(head1->val < head2->val) {
curr->next = head1;
curr = curr->next;
if(head1) head1 = head1->next;
} else {
curr->next = head2;
curr = curr->next;
if(head2) head2 = head2->next;
}
}
return start->next;
}
我无法打印&#39; hi&#39;在控制台窗口上。此外,head1和head2不是NULL值。 请帮助。 更新:能够看到&#39; hi&#39;现在
答案 0 :(得分:0)
首先,你正在破坏head1和head2因为你写了
curr->next = head1;
以后:
curr->next = head2;
所以你要混合两者,最后你可能会有一些记忆泄漏。
因此,您希望将两个列表组合到一个新列表中。所以试试这个:
ListNode *merge_sorted_list(ListNode *head1, ListNode *head2)
{
ListNode* pReturn = new ListNode();
ListNode* tempRet = pReturn;
ListNode* temp1 = head1;
ListNode* temp2 = head2;
while(temp1 != nullptr || temp2 != nullptr)
{
if(temp1 && temp2)
{
if(temp1->val < temp2->val)
{
tempRet->next = new ListNode(temp1); //the constructor should copy the ListNode value
tempRet = tempRet->next;
temp1 = temp1->next;
}
else if(temp1->val > temp2->val)
{
tempRet->next = new ListNode(temp2);
tempRet = tempRet->next;
temp2 = temp2->next;
}
else //doubled value
{
temp1 = temp1->next;
}
}
else if(temp1)
{
while(temp1)
{
tempRet->next = new ListNode(temp1);
tempRet = tempRet -> next;
temp1 = temp1->next;
}
}
else if(temp2)
{
while(temp2)
{
tempRet->next = new ListNode(temp2);
tempRet = tempRet -> next;
temp2 = temp2->next;
}
}
}
return pReturn;
}