我写了一个函数来合并2个排序的链表。但在我知道我提出的逻辑是否正确之前,我遇到了一个无限循环,只要函数被调用。我不知道为什么会这样。下面是代码:
ListNode *merge_sorted_list(ListNode *head1, ListNode *head2) {
cout<<"hin";
ListNode *curr = new ListNode(-1);
ListNode *start = curr;
cout<<"hin";
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;
}
我无法在控制台窗口上打印"hi"。另外,head1和head2不是NULL值。请帮助。更新:现在能够看到"嗨"。
首先,你破坏了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;
}