2-11. 两个有序链表序列的合并(15)
时间限制
500 ms
内存限制
80000 kB
代码长度限制
8000 B
判题程序
Standard
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
输入格式说明:
输入分2行,分别在每行给出由若干个正整数构成的非降序序列,用-1表示序列的结尾(-1不属于这个序列)。数字用空格间隔。
输出格式说明:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出“NULL”。
样例输入与输出:
序号 | 输入 | 输出 |
1 |
1 3 5 -1 2 4 6 8 10 -1 |
1 2 3 4 5 6 8 10 |
2 |
1 2 3 4 5 -1 1 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> #include <malloc.h> typedef struct Node { int dex; //int cof; struct Node * Next; }node; int main() { //Qlink newLink; //newLink=(Link*)malloc(sizeof(Link)); struct Node *head,*tail; head=(node*)malloc(sizeof(node)); tail=(node*)malloc(sizeof(node)); tail->Next=NULL; head->Next=tail; struct Node *pthis,*pthat; pthis=head;pthat=pthis; //第一个链表 int dex; while(scanf("%d",&dex)){ pthis=(node*)malloc(sizeof(node)); pthis->dex=dex; pthis->Next=pthat->Next; pthat->Next=pthis; pthat=pthis; if(dex==-1)break; } //第二个链表 struct Node *head1,*tail1; head1=(node*)malloc(sizeof(node)); tail1=(node*)malloc(sizeof(node)); tail1->Next=NULL; head1->Next=tail1; pthis=head1;pthat=pthis; getchar(); while(scanf("%d",&dex)){ pthis=(node*)malloc(sizeof(node)); pthis->dex=dex; pthis->Next=pthat->Next; pthat->Next=pthis; pthat=pthis; if(dex==-1)break; } //遍历 pthat=head->Next; pthis=head1->Next; if(pthat->dex==-1&&pthis->dex==-1)printf("NULL\n");//两条都空 else if(pthat->dex==-1&&pthis->dex!=-1)//一条空输出另一条非空的 { while(pthis!=NULL&&pthis->Next->Next!=NULL){ printf("%d",pthis->dex); if(pthis->Next->Next->Next!=NULL)printf(" "); else printf("\n"); pthis=pthis->Next; } } else if(pthis->dex==-1&&pthat->dex!=-1) { while(pthat!=NULL&&pthat->Next->Next!=NULL){ printf("%d",pthat->dex); if(pthat->Next->Next->Next!=NULL)printf(" "); else printf("\n"); pthat=pthat->Next; } } else { struct Node *small=(pthat->dex>pthis->dex)?pthis:pthat; struct Node *big=(pthat->dex>pthis->dex)?pthat:pthis; struct Node *last=(pthat->dex>pthis->dex)?pthat:pthis; //printf("%d %d",small->dex,big->dex); pthis=small; pthat=big; while(pthis->dex<=pthat->dex&&pthis->dex!=-1&&pthat->dex!=-1) { last=pthis; pthis=pthis->Next; if(pthis->dex>=pthat->dex){ struct Node *newNode=(node*)malloc(sizeof(node)); newNode->dex=pthat->dex; newNode->Next=pthis; last->Next=newNode; pthis=last->Next; pthat=pthat->Next; } } //如果samll链表用完了(small链表较短) if(pthat->dex!=-1) { last->Next=pthat; } //遍历small last=small; while(last->dex!=-1) { printf("%d",last->dex); if(last->Next->dex==-1)printf("\n"); else printf(" "); last=last->Next; } } //free(pthat); free(pthis);free(head);free(tail);free(head1);free(tail1); return 0; }
时间: 2024-11-05 20:46:11