浅枫


私信TA

用户名:a1105054657

访问量:28400

签 名:

生命不止,奋斗不息

等  级
排  名 125
经  验 7461
参赛次数 3
文章发表 26
年  龄 21
在职情况 学生
学  校 抚顺职业技术学院
专  业 电气自动化技术专业

  自我简介:

潺潺弱弱的小菜鸡一只!

解题思路:
1)首先先给链表取长度

2)给两个链表的各个节点赋值

3)查找a链表中与b链表学号相同的节点进行释放节点

4)遍历a链表中的所有数据
注意事项:

1)再给链表释放的过程中注意利用临时变量保存好链表的下一个节点的地址,以免发生不必要的错误

2)链表释放过程中要考虑各种边界条件(比如:链表头)。
参考代码:

#include<stdio.h>
#include<stdlib.h>

typedef struct Student {
	int id;   //学号
	int score;  //成绩
	struct s_a *Next;
} sa, sb;



int main() {
	int id, score, n, m, i;
	sa *heada = NULL;
	sb *headb = NULL;

	scanf("%d%d", &n, &m);                                           //两个链表的长度
/************************************************************/		//链表a赋值
	for( i=1; i<=n; i++) {
		sa *pa = (sa*)malloc(sizeof(sa));
		scanf("%d%d", &id, &score);
		pa->id = id;
		pa->score = score;
		pa->Next = NULL;
		sa *lasta = heada;
		if(lasta) {
			while(lasta->Next) {
				lasta = lasta->Next ;
			}
			lasta->Next = pa;
		} else {
			heada = pa;
		}
	}
/************************************************************/		//链表b赋值
	for( i=1; i<=m; i++) {
		sb *pb = (sb*)malloc(sizeof(sb));
		scanf("%d%d", &id, &score);
		pb->id = id;
		pb->score = score;
		pb->Next = NULL;
		sb *lastb = headb;
		if(lastb) {
			while(lastb->Next ) {
				lastb = lastb->Next ;
			}
			lastb->Next = pb;
		} else {
			headb = pb;
		}
	}
/************************************************************/		//查找相同学号并释放链表
	sa *ta = heada;
	sb *tb = headb;
	for( tb; tb; tb=tb->Next ){
		ta = heada;
		sa *qa; //临时变量
		for( ta, qa=NULL; ta; qa=ta, ta=ta->Next ){
			if(ta->id == tb->id ){
				if(qa){
					qa->Next = ta->Next ;
				} else {
					heada = ta->Next ;
				}
				free(ta);
				n--;
				break;
			}
		}
	}
	
/************************************************************/		//遍历显示
	ta = heada;
	printf("%d\n", n);
	for( ta; ta; ta=ta->Next ) {
		printf("%d %d\n", ta->id ,ta->score  );
	}

	return 0;
}


 

0.0分

4 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区