gpt4 book ai didi

c++ - 合并两个排序的链表

转载 作者:行者123 更新时间:2023-11-28 06:06:42 26 4
gpt4 key购买 nike

我正在尝试编写一个程序来合并两个已排序的链表。但是最后一个元素根本没有被插入。当尝试在 listA 中的最后一个节点之后插入一个节点时,代码似乎失败了。任何帮助将不胜感激。

  /*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* MergeLists(Node *headA, Node* headB)
{
// This is a "method-only" submission.
// You only need to complete this method
Node *prev;
Node *currentA=headA;
Node *currentB=headB;
Node *next;
if(headA==NULL)
{
return headB;
}
if(headB==NULL)
{
return headA;
}
while(currentA!=NULL && currentB!=NULL)
{
if(currentB->data < currentA->data)
{
Node *new_node=new Node;
new_node->data=currentB->data;
headA=new_node;
new_node->next=currentA;
currentA=new_node;
currentB=currentB->next;
}
else if(currentB->data > currentA->data && currentB->data < currentA->next->data)
{
Node *new_node=new Node;
new_node->data=currentB->data;
next=currentA->next;
prev=currentA;
new_node->next=next;
prev->next=new_node;
currentA=new_node;
currentB=currentB->next;

}
else
{
currentA=currentA->next;

}
if(currentA->next==NULL)
{
Node *new_node=new Node;
new_node->data=currentB->data;
prev=currentA;
prev->next=new_node;
new_node->next=NULL;
currentA=new_node;
currentB=currentB->next;
}
}
return headA;
}

输入:

1 (No of test cases)
2 (Length of list A)
2 4
4 (Length of list B)
1 3 5 7

预期输出:

1 2 3 4 5

实际输出:

Runtime error

最佳答案

我认为真正的问题在于您的输入。

1(测试用例数)

2(列表A的长度)

2 4

2(列表 B 的长度)

1 3 5

列表 B 的长度应为 3。正如您在输入中提到的 2。您的输出仅包含列表 B 中的 2 个元素。

请检查正确输入如下:

1(测试用例数)

2(列表A的长度)

2 4

3(列表B的长度)

1 3 5

关于c++ - 合并两个排序的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32239521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com