学生链表表合并c语言,[编程入门]链表合并-题解(C语言代码)

#includestruct node // 链表上结点的数据结构

{

int num;//学号

float score;//姓名

struct node *next; //指针

};

/*函数,初始化一个无序链表*/

struct node *creat(int n) //n为结点数目

{

struct node *head,*p1,*p2; //head为头结点,p1为新插入的结点,p2为尾结点

head=NULL;int i;

for(i=1;i<=n;i++)

{

p1=(struct node *)malloc(sizeof(struct node));

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

if(head==NULL)

{

head=p1; p2=p1; //这一部是初始化了头结点

}

else{

p2->next=p1; //当前尾结点与新节点连接

p2=p1;//尾结点更新为新插入的结点

}

}

if(head) p2->next=NULL; //头结点不为NULL,尾结点p2里存放的下一个结点指针为NULL

return (head); //返回头结点

}

/*合并两个链表*/

struct node *merge(struct node *p1,struct node*p2) //参数表为两个链表的头结点

{

if(p1==NULL || p2==NULL) return NULL;

struct node *tail; //p1的尾结点tail

tail=p1;

while(tail->next != NULL)

{

tail=tail->next;

}//循环结束时,tail为第一个链表的尾结点

tail->next=p2;//使tail与第二个链表的头结点相连接

return (p1);//返回第一个链表的头结点即可

}

/*输出链表*/

void print(struct node *head)

{

struct node *p;

p=head;

while(p!=NULL)

{

printf("%d %.f\n",p->num,p->score); //输出学号与成绩

p=p->next;// 循环控制

}

}

void deletechain(struct node *head) // 释放链表上各结点占用的内存空间

{

struct node *p1;

while(head)

{

p1 = head;

head = head->next;

free( (void *)p1 ); //free掉所有节点

}

}

/*对合并后的链表排序*/

void *sort(struct node *head)

{

if(head==NULL) return NULL;

struct node *pre=NULL;

struct node *cur=NULL;

struct node tmp; //交换用到的中间变量

for(pre=head;pre->next!=NULL;pre=pre->next) //选择排序

{

for(cur=pre->next;cur!=NULL;cur=cur->next)

{

if(pre->num > cur->num)

{

tmp=*pre; *pre=*cur; *cur=tmp; //数据域交换

tmp.next=pre->next; pre->next=cur->next;cur->next=tmp.next;//指针域交换

}

}

}

}

int main()

{

int n,m,i;

scanf("%d%d",&n,&m);

struct node *head1,*head2;

head1=creat(n);

head2=creat(m);

head1=merge(head1,head2);

sort(head1);

print(head1);

deletechain(head1);

return 0;

}

```

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值