解题思路:phead1 phead2来接受两个链表,phead3来合并
注意事项:
参考代码:
#include<stdio.h> #include<stdlib.h> struct student { int num; struct student *pnext; }; struct student* creat(int n) //接受链表 { struct student *pnew,*pend,*phead; for(int i=0;i<n;i++) { pnew=(struct student*)malloc(sizeof(struct student)); if(scanf("%d",&pnew->num)); pnew->pnext=NULL; if(i==0) { phead=pnew; pend=pnew; } else { pend->pnext=pnew; pend=pnew; } } return phead; } struct student* combine(struct student *phead1,struct student *phead2) //合并 { struct student *p=phead1,*q=phead2,*phead3=NULL,*ptemp; while(p!=NULL&&q!=NULL) //直到p和q都结束才跳出循环 { if(p->num>q->num) //第一个if到q或p其中一个为NULL就结束了 { if(phead3==NULL) { phead3=q; ptemp=phead3; } else { ptemp->pnext=q; ptemp=q; } q=q->pnext; } else { if(phead3==NULL) { phead3=p; ptemp=phead3; } else { ptemp->pnext=p; ptemp=p; } p=p->pnext; } if(q==NULL) //剩余的一串链表 ptemp->pnext=p; else ptemp->pnext=q; } return phead3; } void print(struct student *phead3) { struct student *ptemp=phead3; while(ptemp!=NULL) { printf("%d ",ptemp->num); ptemp=ptemp->pnext; } } int main() { int n,num; struct student *phead1=NULL,*phead2=NULL,*phead3=NULL; while(scanf("%d",&n)!=EOF) //有多个2组 { phead1=creat(n); if(scanf("%d",&num)); phead2=creat(num); phead3=combine(phead1,phead2); print(phead3); printf("\n"); //格式,测试一次性有大量数据 } return 0; }
0.0分
1 人评分