5-15 两个有序链表序列的合并

来源:互联网 发布:天刀清纯萝莉捏脸数据 编辑:程序博客网 时间:2024/06/05 20:50

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

输入格式:

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

输出格式:

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

输入样例:

1 3 5 -12 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10

#include<stdio.h>#include<stdlib.h>struct node{int num;struct node* next;};typedef struct node * list;list scan(){list l;list head=NULL,tail=NULL;int n;while(scanf("%d",&n)){if(n==-1) return head;if(head==NULL){head=(list)malloc(sizeof(struct node));head->num=n;head->next=NULL;tail=head;}else{list t=(list)malloc(sizeof(struct node));t->num=n;t->next=NULL;tail->next=t;tail=t;}}}void merge(list l1,list l2){int flag=0;list temp;    while(l1&&l2)    {    if(!flag) flag=1;    else printf(" ");     if(l1->num<=l2->num)     {     printf("%d",l1->num);     temp=l1;     l1=l1->next;     free(temp); }     else     {     printf("%d",l2->num);     temp=l2;     l2=l2->next;     free(temp); }}while(l1){       if(!flag) flag=1;    else printf(" ");printf("%d",l1->num);temp=l1;    l1=l1->next;free(temp);}while(l2){if(!flag) flag=1;    else printf(" ");printf("%d",l2->num);temp=l2;    l2=l2->next;    free(temp);}if(!flag) printf("NULL");}int main(){list l1,l2;l1=NULL;l2=NULL;l1=scan();l2=scan();merge(l1,l2);}


0 0
原创粉丝点击