#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student //声明结构体
{
int num;
struct student *pnext;
}stu,*pstu;
void link_sort_insert(pstu *,pstu *,int); //建立有序链表
void link_show(pstu );
void link1_merge_link2(pstu *phead1,pstu *ptail1,pstu *phead2,pstu *ptail2); //把链表2合并到1
void main(){
pstu phead1,ptail1,phead2,ptail2;
int i;
phead1 = NULL;
ptail1 = NULL;
phead2 = NULL;
ptail2 = NULL;
while(scanf("%d",&i) != EOF){ //建立链表1
link_sort_insert(&phead1,&ptail1,i);
}
link_show(phead1);
while(scanf("%d",&i) != EOF){ //建立链表2
link_sort_insert(&phead2,&ptail2,i);
}
link_show(phead2);
link1_merge_link2(&phead1,&ptail1,&phead2,&ptail2); //合并
link_show(phead1);
system("pause");
}
void link_sort_insert(pstu *phead,pstu *ptail,int i){ //建立有序链表
pstu pnew,pcur,ppre;
pnew = (pstu)malloc(sizeof(stu));
memset(pnew,0,sizeof(stu));
pnew->num = i;
if(*phead == NULL){
*phead = pnew;
*ptail = pnew;
}
else if((*phead)->num > i){
pnew->pnext = *phead;
*phead = pnew;
}
else{
pcur = *phead;
ppre = *phead;
while(pcur != NULL){
if(pcur->num > i){
pnew->pnext = ppre->pnext;
ppre->pnext = pnew;
break;
}
ppre = pcur;
pcur = pcur->pnext;
}
if(pcur == NULL){
(*ptail)->pnext = pnew;
*ptail = pnew;
}
}
}
void link1_merge_link2(pstu *phead1,pstu *ptail1,pstu *phead2,pstu *ptail2){ //把链表2合并到1
pstu i,ppre,pcur;
pcur = *phead1; //pcur ppre 指向链表1头结点
ppre = *phead1;
while(*phead2 != NULL){
i = *phead2; //记录链表2头结点的当前位置
*phead2 = (*phead2)->pnext; //链表头结点指向下1个结点
if((*phead1)->num > i->num){ //判断链表1头结点是否大于i
i->pnext = *phead1; //如果大于,插入头结点
*phead1 = i;
pcur = *phead1; //pcur ppre 重新指向链表1头结点
ppre = *phead1;
}
else{ //链表1头结点不大于i
while(pcur != NULL){
if(pcur->num > i->num){ //判断链表1当前节点pcur是否大于i
i->pnext = ppre->pnext; //若大于i 则插入,循环结束,pcur不动
ppre->pnext = i;
break;
}
ppre = pcur; //若cur <=i 记录当前pcur,pcur指向下一个位置
pcur = pcur->pnext;
}
if(pcur == NULL){ //如果链表1达到尾结点,i插入到链表1尾节点
(*ptail1)->pnext = i;
*ptail1 = i;
}
}
}
*phead2 = NULL; //释放
*ptail2 = NULL;
}
void link_show(pstu phead){
pstu pshow;
pshow = phead;
if(phead == NULL)
{
printf("no exsit\n");
return;
}
while(pshow != NULL){
printf("%d ",pshow->num);
pshow = pshow->pnext;
}
putchar('\n');
}
将两个单向有序链表合并成一个单向有序链表
最新推荐文章于 2020-07-14 21:16:54 发布