将两个有序的单链表合并为一个有序单链表并输出其长度

发布网友 发布时间:2022-04-22 06:24

我来回答

1个回答

热心网友 时间:2022-04-24 04:22

#include<stdio.h>
#include<stdlib.h>
struct node
{int x;
 struct node *next;
};
struct node*creat()
{int x,x1=-999999;
 struct node *h,*p,*q;
 h=(struct node*)malloc(sizeof(struct node));
 h->next=NULL;
 q=h;
 scanf("%d",&x);
 while(x>x1)
 {p=(struct node*)malloc(sizeof(struct node));
  p->x=x;
  q->next=p;
  q=p;
  x1=x;
  scanf("%d",&x);
 }
 q->next=NULL;
 return h;
}
void prt(struct node*p,char s[])
{printf("%s\n",s);
 for(p=p->next;p;p=p->next)
   printf("%d ",p->x);
 printf("\n");  
}
struct node*merge(struct node*h1,struct node*h2)
{struct node*h,*p;
 p=h=h1;
 h1=h1->next,h2=h2->next;
 for(;h1&&h2;)
   {if(h1->x<h2->x)
    {p->next=h1;
     h1=h1->next;
    }
    else
    {p->next=h2;
     h2=h2->next;
    }
    p=p->next;
   }
 p->next=h1?h1:h2;  
 return h;
}
int main()
{struct node *h1,*h2,*h;
 h1=creat();
 h2=creat();
 prt(h1,"Table 1:");
 prt(h2,"Table 2:");
 h=merge(h1,h2);
 prt(h,"Table 1 & 2:");
 return 0;
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com