原题链接:[编程入门]链表合并
解题思路:
注意事项:
参考代码:
#include<stdio.h>
#include<stdlib.h>
//构建节点的结构体
typedef struct stu{
int id;
int score;
struct stu* next;
}stu;
//创建节点
stu *create_node(int id,int score){
stu* node = (stu*)malloc(sizeof(stu));//申请内存
node->score = score;
node->id = id;
node->next = NULL;
return node;
}
//创建长度为num的单链表
void appendNode(stu** head, int id, float score) {
stu* newNode = create_node(id, score);
if (*head == NULL) {
*head = newNode;
return;
}
stu* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
stu* mergelists(stu* a,stu* b){
//加多一个节点
//注意指针使用->
stu*c = (stu*)malloc(sizeof(stu));
stu* tail = c;
tail->next = NULL;
tail->next = NULL;
while(a!= NULL && b != NULL){
//分别比较学号按照升序排列
if(a->id <= b->id){
tail->next = a;
a = a->next;
}
else{
tail->next = b;
b = b->next;
}
tail = tail->next;
}
if (a != NULL) {
tail->next = a;
}
else{
tail->next = b;
}
stu *result = c->next;
return result;
}
void sortlist(stu *head){
if(head == NULL)return;
int swapped;
stu* ptr1;
stu* lptr = NULL;
do {
swapped = 0;
ptr1 = head;
//运用冒泡排序法
while (ptr1->next != lptr) {
if (ptr1->id > ptr1->next->id) {
// 交换节点数据
int tempId = ptr1->id;
int tempScore = ptr1->score;
ptr1->id = ptr1->next->id;
ptr1->score = ptr1->next->score;
ptr1->next->id = tempId;
ptr1->next->score = tempScore;
swapped = 1;
}
ptr1 = ptr1->next;
}
//从第下一个索引开始查找排序
lptr = ptr1;
}
while (swapped);
}
void printList(stu* head) {
stu* temp = head; // temp 是结构体指针
while (temp != NULL) {
printf("%d %d\n", temp->id, temp->score); // 正确使用 ->
temp = temp->next; // 正确使用 ->
}
}
int main(){
stu* listA = NULL;
stu* listB = NULL;
stu* mergedList = NULL;
int N,M;
scanf("%d %d",&N,&M);
for(int i=0;i<N;i++){
int id,score;
scanf("%d %d",&id,&score);
appendNode(&listA,id,score);
}
for(int j=0;j<M;j++){
int id,score;
scanf("%d %d",&id,&score);
appendNode(&listB,id,score);
}
//先对list A list B 进行排序
sortlist(listA);
sortlist(listB);
mergedList = mergelists(listA, listB);
printList(mergedList);
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复