【问题标题】:merge 2 sorted linked-list合并 2 个排序的链表
【发布时间】:2015-12-31 10:08:54
【问题描述】:

我的代码有什么问题?SortedMerge 方法获取两个链表的头部,我使用了节点指针 z,它指向我们正在处理的节点,指针头被初始化为指向 z,因为最后 z将指向最后一个节点....我将返回最终排序合并列表的头部。

 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) ;
 }

【问题讨论】:

    标签: merge linked-list


    【解决方案1】:

    为您提供简洁的代码,

    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;
      }
    }
    

    见说明how it works

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-23
      • 2014-09-18
      • 2020-04-03
      • 2011-05-17
      • 2011-01-21
      相关资源
      最近更新 更多