7-2 两个有序链表序列的合并

来源:互联网 发布:大型网络端游排行榜 编辑:程序博客网 时间:2024/06/05 19:59

7-2 两个有序链表序列的合并

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例:

1 3 5 -1
2 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10

#include <stdio.h>#include <stdlib.h>typedef struct node{    int data;    struct node *next;}node,*Lnode;Lnode creat(){  Lnode  l,p,s;  int n;  l=(Lnode)malloc(sizeof( struct node));  l->next=NULL;  p=l;  while(scanf("%d",&n) && n!=-1)//控制输入的数据到-1截止  {     s=(Lnode)malloc(sizeof(struct node));     s->next=NULL;     s->data=n;     p->next=s;     p=s;  }  return l;}Lnode hebing(Lnode head1,Lnode head2){    Lnode pa,pb,pc;    if(head1==NULL && head2==NULL)//控制空链表        return NULL;    else if(head1==NULL && head2 !=NULL)        return head1;    else if(head1!=NULL && head2==NULL)        return head2;    pa=head1->next;    pb=head2->next;    pc=head1;    free(head2);    while(pa && pb)    {       if(pa->data <= pb->data)       {           pc->next=pa;           pc=pa;           pa=pa->next;       }       else       {           pc->next=pb;           pc=pb;           pb=pb->next;       }    }    if(pa)    {        pc->next=pa;    }    if(pb)    {        pc->next=pb;    }    return head1;}void show(Lnode head1){    Lnode q;    q=head1->next;    while(q!=NULL)    {        if(q->next==NULL)            printf("%d\n",q->data);        else             printf("%d ",q->data);        q=q->next;    }}int main(){    Lnode head1,head2;    head1=creat();    head2=creat();    head1=hebing(head1,head2);    if(head1->next==NULL)//head1->next==NULL;        printf("NULL\n");//如果为空链表就输出NULL;    else    show(head1);    return 0;}
原创粉丝点击