有序链表的合并

来源:互联网 发布:亚龙湾酒店推荐 知乎 编辑:程序博客网 时间:2024/05/14 02:55

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

输入格式说明:

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

输出格式说明:

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

样例输入与输出:

序号输入输出1
1 3 5 -12 4 6 8 10 -1
1 2 3 4 5 6 8 10
2
1 2 3 4 5 -11 2 3 4 5 -1
1 1 2 2 3 3 4 4 5 5
3
-1-1
NULL

提交代码
#include<stdio.h>#include<stdlib.h>#define LEN sizeof(struct node)struct node{int num;struct node *next;};struct node *creat(){struct node *p1,*p2,*head;int i=0;head=NULL;while(1){p1=(struct node*)malloc(LEN);        scanf("%d",&p1->num);if(p1->num==-1)break;if(i++==0)head=p1;elsep2->next=p1;p2=p1;}free(p1);if(i)    p2->next=NULL;//为空链表的时候return head;}struct node *combine(struct node *p1,struct node *p2){struct node *p,*q,*head;head=NULL;int i=0;while(p1!=NULL && p2!=NULL){while( p1->num >= p2->num ){p=(struct node*)malloc(LEN);p->num=p2->num;if(i++==0)head=p;elseq->next=p;q=p;p2=p2->next;if(p2==NULL)break;}if(p1==NULL || p2==NULL)break;while( p1->num < p2->num){p=(struct node*)malloc(LEN);p->num=p1->num;if(i++==0)head=p;elseq->next=p;q=p;p1=p1->next;if(p1==NULL)break;}}while(p1!=NULL){p=(struct node*)malloc(LEN);p->num=p1->num;if(i++==0)head=p;elseq->next=p;q=p;p1=p1->next;}while(p2!=NULL){p=(struct node*)malloc(LEN);p->num=p2->num;if(i++==0)head=p;elseq->next=p;q=p;p2=p2->next;}if(i)p->next=NULL;return head;}int main(){struct node *p1,*p2,*head;p1=creat();p2=creat();head=combine(p2,p1);if(head!=NULL){while(head->next!=NULL){printf("%d ",head->num);head=head->next;}printf("%d\n",head->num);}elseprintf("NULL\n");return 0;}

0 0
原创粉丝点击