有两个链表a,b。设结点中包含学号、姓名。从a链表中删去与b链表中所有相同学号的那些结点。代码怎么写
时间: 2024-02-22 13:59:17 浏览: 97
以下是C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
int id; // 学号
char name[20]; // 姓名
struct student *next; // 指向下一个结点的指针
};
// 从链表中删除指定学号的结点
struct student* delete_node(struct student *head, int id) {
struct student *p, *prev;
prev = NULL;
p = head;
while (p != NULL) {
if (p->id == id) {
if (prev == NULL) {
head = p->next; // 如果是头结点,直接删除
}
else {
prev->next = p->next; // 如果不是头结点,修改上一个结点的next指针
}
free(p); // 释放内存
p = prev->next; // 继续遍历下一个结点
}
else {
prev = p;
p = p->next;
}
}
return head;
}
// 从链表中删除与另一个链表中相同学号的结点
struct student* delete_same_nodes(struct student *a, struct student *b) {
struct student *p;
p = b;
while (p != NULL) {
a = delete_node(a, p->id); // 从链表a中删除与链表b中相同学号的结点
p = p->next;
}
return a;
}
// 打印链表
void print_list(struct student *head) {
struct student *p;
p = head;
while (p != NULL) {
printf("%d %s\n", p->id, p->name);
p = p->next;
}
}
int main() {
struct student *a, *b;
struct student *p1, *p2;
int i;
// 初始化链表a
a = (struct student*)malloc(sizeof(struct student));
a->id = 1001;
strcpy(a->name, "Tom");
a->next = NULL;
p1 = a;
for (i = 0; i < 4; i++) {
p2 = (struct student*)malloc(sizeof(struct student));
p2->id = 1002 + i;
sprintf(p2->name, "Student%d", i+1);
p2->next = NULL;
p1->next = p2;
p1 = p2;
}
// 初始化链表b
b = (struct student*)malloc(sizeof(struct student));
b->id = 1002;
strcpy(b->name, "Jerry");
b->next = NULL;
p1 = b;
for (i = 0; i < 3; i++) {
p2 = (struct student*)malloc(sizeof(struct student));
p2->id = 1003 + i;
sprintf(p2->name, "Student%d", i+5);
p2->next = NULL;
p1->next = p2;
p1 = p2;
}
printf("链表a:\n");
print_list(a);
printf("\n链表b:\n");
print_list(b);
// 从链表a中删除与链表b中相同学号的结点
a = delete_same_nodes(a, b);
printf("\n删除后的链表a:\n");
print_list(a);
// 释放内存
p1 = a;
while (p1 != NULL) {
p2 = p1->next;
free(p1);
p1 = p2;
}
p1 = b;
while (p1 != NULL) {
p2 = p1->next;
free(p1);
p1 = p2;
}
return 0;
}
```
运行结果:
```
链表a:
1001 Tom
1002 Student1
1003 Student2
1004 Student3
1005 Student4
链表b:
1002 Jerry
1003 Student5
1004 Student6
1005 Student7
删除后的链表a:
1001 Tom
```
这个程序定义了一个结构体 `student` 来存储学生信息,然后用两个链表 `a` 和 `b` 分别存储学生信息。使用 `delete_node` 函数来从链表中删除指定学号的结点,然后使用 `delete_same_nodes` 函数来从链表 `a` 中删除与链表 `b` 中相同学号的结点。最后再输出链表 `a` 的内容。注意在释放内存时需要遍历整个链表。
阅读全文