300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 链表c语言代码题库排坐标 [编程入门]链表合并-题解(C语言代码)

链表c语言代码题库排坐标 [编程入门]链表合并-题解(C语言代码)

时间:2021-10-02 21:26:58

相关推荐

链表c语言代码题库排坐标 [编程入门]链表合并-题解(C语言代码)

```c

/* 题目描述

已有a、b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按学号升序排列。

输入

第一行,a、b两个链表元素的数量N、M,用空格隔开。 接下来N行是a的数据 然后M行是b的数据 每行数据由学号和成绩两部分组成

输出

按照学号升序排列的数据

样例输入

2 3

5 100

6 89

3 82

4 95

2 10

样例输出

2 10

3 82

4 95

5 100

6 89 */

#include#include#define LEN sizeof(struct Node)

struct Node *Creat_Node(int n);//创建链表函数

struct Node *merge_list(struct Node *k,struct Node *t,int n);//合并链表函数

struct Node *sort(struct Node *x,int len);// 排序函数

struct Node *Show(struct Node *x);//打印链表函数

// 定义一个结构体,作为节点

struct Node

{

int num;//学号,此题为整型

float score;//分数,浮点型

struct Node *next;//next是指针变量,指向结构体变量

};

struct Node *Creat_Node(int n)

{

int num;

float score;

struct Node *pTail,*p1,*head;//head是指向链表第一个节点的指针变量

head=(struct Node *)malloc(LEN);

pTail=head;//表示还没有链表

//建立节点

pTail->next=NULL;

while (n--)

{

p1=(struct Node *)malloc(LEN);//p1是链表的第一个地址

scanf("%d%f",&num,&score);//获取第一个节点数据

p1->num=num;

p1->score=score;

pTail->next=p1;

p1->next=NULL;

pTail=p1;

}

return head;//把链表首地址返回

}

/* 按照学号升序排列的数据

思路:首先合并两个链表,然后对合并后的链表进行选择排序

*/

struct Node *merge_list(struct Node *k,struct Node *t,int n)//k,t接受地址a,b,并且返回合并后的链表的首地址

{

// 找到a链表的尾节点,让它指向b链表的头结点,并且释放b

// 定义一个指针,让它去找尾节点

struct Node *pre;

pre=k->next;

for(int i=1;inext;

}

pre->next=t->next;

// free(t);//释放b的头结点

return k;//返回合并后的头结点

}

// 排序(冒泡法)

struct Node *sort(struct Node *x,int len)

{

int temp,temp1,i,j;

struct Node *pre=NULL,*cur=NULL;

for(i=0,pre=x->next;inext)

{

for(j=i+1,cur=pre->next;jnext)

{

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

{

temp=pre->num;

temp1=pre->score;

pre->num=cur->num;

pre->score=cur->score;

cur->num=temp;

cur->score=temp1;

}

}

}

return x;

}

struct Node *Show(struct Node *x)

{

struct Node *t;

t=x->next;

while(t!=NULL)

{

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

t=t->next;

}

}

int main()

{

struct Node *a,*b,*merge_node,*t;

int N,M;

scanf("%d%d",&N,&M);

//建立a链表

a=Creat_Node(N);

//建立b链表

b=Creat_Node(M);

merge_node=merge_list(a,b,N);

Show(merge_node);

t=sort(merge_node,N+M);

Show(merge_node);

return 0;

}

```

有疑问可以留言讨论

0.0分

0 人评分

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。