原题链接:数据结构-有序线性表的有序合并
解题思路: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 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复