链表合并 c语言,链表合并(初学者)

C/C++ code#include

#include

#include

//#define NULL 0 没有必要

struct student

{

int num; //学号

int score; //分数

struct student *next; //下一结点

};

struct student *creat(void)

{

struct student *p1,*p2,*head;

int n=0;

p1 = p2 = (struct student *)malloc(sizeof(struct student)); //创建头结点

head= NULL;

printf("\n请输入学号与分数,以0结束输入!\n");//最好要有输入提示

scanf("%d,%d",&p1->num,&p1->score);

while (p1->num!=0) //输入0 结束

{

n=n+1;

if(n==1) //判断头结点

head=p1;

else

p2->next=p1;

p2=p1; //保存前驱结点

p1=(struct student *)malloc(sizeof(struct student)); //开辟新的结点

scanf("%d,%d",&p1->num,&p1->score);

}

p2->next=NULL;

return head;

}

struct student *insert(struct student *head,struct student *pi) //插入结点

{

struct student *pf,*pb;

pb=pf=head;

if(head==NULL) //空链表 插入

{

head=pi;

head->next=NULL;

return head;

}

while((pb->next!=NULL)&&(pb->numnum)) //比较大小 按顺序插入

{

pf=pb;

pb=pb->next;

}

if(pb->num>=pi->num) //找到了所要插入的位置 (从小到大)

{

if(pb==head) //插入到 链表 的 头

{

head=pi;

pi->next=head;

}

else

{ //插入到普通位置

pf->next=pi;

pi->next=pb;

}

}

else //插入到链表的 尾

{

pb->next=pi;

pi->next=NULL;

}

return head;

}

struct student *sort(struct student *heada,struct student *headb)// 若链表a是有序的 插入排序

{

struct student *pb,*pb1;

pb = pb1 = headb;

if((heada == NULL)&&(headb != NULL))

{

heada = headb;

}

else if((headb == NULL)&&(heada != NULL))

{

headb = heada;

}

else

{

while(pb1!= NULL) //控制listb,将listb中的结点依次插入lista中

{

pb = pb1;

pb1 = pb1->next;

heada=insert(heada,pb);

}

}

return heada;

}

void print(struct student *head)

{

struct student *p;

p=head;

while(p!=NULL)

{

printf("%d,%d\n",p->num,p->score);

p=p->next;

}

}

int main(int argc,char *argv[])

{

struct student *heada,*headb,*pb;

printf("input the list a:");

heada=creat(); //创建链表a

print(heada);

printf("\ninput the list b:");

headb=creat(); //创建链表b

print(headb);

printf("\nthe new list :\n");

pb = sort(heada,headb); //升序合并链表a和b

print(pb);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值