解题思路:
在 deleteNodes函数中,首先遍历链表b,然后在每次遍历链表b时,再遍历链表a。如果发现链表a中有与链表b中相同学号的节点,将其删除。
对于链表a,使用 currA指针和 prevA指针来遍历链表a。如果当前节点的学号与链表b中的某个节点的学号相同,将当前节点删除,并更新指针。最后,将链表b中的所有节点都遍历完毕后,链表a中相同学号的节点都被删除。
注意事项:
释放链表空间
参考代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int id;
int score;
struct Node* next;
} Node;
Node* createNode(int id, int score) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->id = id;
newNode->score = score;
newNode->next = NULL;
return newNode;
}
void insert(Node** head, int id, int score) {
Node* newNode = createNode(id, score);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void deleteNodes(Node** head, Node* bHead) {
Node* currB = bHead;
while (currB != NULL) {
Node* currA = *head;
Node* prevA = NULL;
while (currA != NULL) {
if (currA->id == currB->id) {
Node* temp = currA;
if (prevA == NULL) {
*head = currA->next;
currA = currA->next;
} else {
prevA->next = currA->next;
currA = currA->next;
}
free(temp);
} else {
prevA = currA;
currA = currA->next;
}
}
currB = currB->next;
}
}
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d %d\n", temp->id, temp->score);
temp = temp->next;
}
}
void freeList(Node* head) {
Node* curr = head;
while (curr != NULL) {
Node* temp = curr;
curr = curr->next;
free(temp);
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
Node* aHead = NULL;
Node* bHead = NULL;
for (int i = 0; i < n; i++) {
int id, score;
scanf("%d %d", &id, &score);
insert(&aHead, id, score);
}
for (int i = 0; i < m; i++) {
int id, score;
scanf("%d %d", &id, &score);
insert(&bHead, id, score);
}
deleteNodes(&aHead, bHead);
int k = 0;
Node* temp = aHead;
while (temp != NULL) {
k++;
temp = temp->next;
}
printf("%d\n", k);
printList(aHead);
freeList(aHead);
freeList(bHead);
return 0;
}
0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复