我的代码出了什么问题?方法SortedMerge获取了两个链表的头,我使用了节点指针z,它将指向我们正在处理的节点,指针头被初始化为指向z,因为最终z将指向最后一个节点,....i返回最终排序合并列表的头。
struct node* SortedMerge(struct node* a, struct node* b)
{
struct node* z=NULL;
struct node *head=z;
while(a!=NULL || b!=NULL)
{
if(a==NULL)
{
return(b);
break;
}
else if(b==NULL)
{
return(a);
break;
}
if(a->data<b->data)
{
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=a->data;
newnode->next=NULL;
z=newnode;
SortedMerge(a->next,b);
}
else if(a->data>b->data)
{
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=b->data;
newnode->next=NULL;
z=newnode;
SortedMerge(a,b->next);
}}
return (head) ;
}发布于 2016-01-02 00:57:37
为您编写简洁的代码,
Node MergeLists(Node list1, Node list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
if (list1.data < list2.data) {
list1.next = MergeLists(list1.next, list2);
return list1;
} else {
list2.next = MergeLists(list2.next, list1);
return list2;
}
}参见description how it works
https://stackoverflow.com/questions/34544718
复制相似问题