帮助递归函数
我有以下代码来合并两个排序的链表:
struct node* merge(struct node* a, struct node* b)
{
struct node dummy;
struct node* tail = &dummy;
dummy.next = NULL;
while(1)
{
if(a == NULL)
{
tail->next = b;
break;
}
else if (b == NULL)
{
tail->next = a;
break;
}
if (a->data <= b->data)
{
MoveNode(&(tail->next), &a);
}
else
{
MoveNode(&(tail->next), &b);
}
tail = tail->next;
}
return(dummy.next);
}
void MoveNode(struct node** destRef, struct node** sourceRef)
{
struct node* newNode = *sourceRef;
*sourceRef = newNode->next;
newNode->next = *destRef;
*destRef = newNode;
}
并且效果很好。我试图将其变成递归方法,这就是我得到的:
struct node* Merge(struct node* a, struct node* b)
{
struct node* result;
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
if (a->data <= b->data)
{
result = Merge(a->next, b);
}
else
{
result = Merge(a, b->next);
}
return(result);
}
但结果中缺少许多节点。怎么了?
I have the following code to merge two sorted linked lists:
struct node* merge(struct node* a, struct node* b)
{
struct node dummy;
struct node* tail = &dummy;
dummy.next = NULL;
while(1)
{
if(a == NULL)
{
tail->next = b;
break;
}
else if (b == NULL)
{
tail->next = a;
break;
}
if (a->data <= b->data)
{
MoveNode(&(tail->next), &a);
}
else
{
MoveNode(&(tail->next), &b);
}
tail = tail->next;
}
return(dummy.next);
}
void MoveNode(struct node** destRef, struct node** sourceRef)
{
struct node* newNode = *sourceRef;
*sourceRef = newNode->next;
newNode->next = *destRef;
*destRef = newNode;
}
And it worked fine. I was trying to make it into a recursive method and this is what I got:
struct node* Merge(struct node* a, struct node* b)
{
struct node* result;
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
if (a->data <= b->data)
{
result = Merge(a->next, b);
}
else
{
result = Merge(a, b->next);
}
return(result);
}
But it has many of the nodes missing in the result. What is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的基本条件是正确的。但是你的递归条件有问题。
当您将
a
的数据与b
的数据进行比较时,您并未将节点a
或节点b
复制到其中结果
。尝试:
Your base conditions are correct. But there is problem with your recursive condition.
When you compare
a
's data withb
's data you are not copying nodea
or nodeb
intoresult
.Try: