解题思路:
首先,需要创建一个链表
typedef struct student { int id; int chengji; struct student* next; }*node, Node; //一般创建链表我们都用typedef struct,因为这样定义结构体变量时, //我们就可以直接可以用node a 来定义结构体指针,Node b来定义结构体变量 //其实就是用 node 代替了struct student * //Node 代替了struct student
其次初始化一个链表,n为链表节点个数。
node creat(int n) { node head, p, q; head = (node)malloc(sizeof(Node)); head->next = NULL; q = head; for (int i = 0; i < n; i++) { p = (node)malloc(sizeof(Node)); scanf("%d%d", &(*p).id, &p->chengji); p->next = q->next; //这里用的链表的后插法 q->next = p; q = p; } return head; }
之后是进行删除
void fun(node h1, node h2) { h2 = h2->next; node p, t = h2; while (h1->next != NULL) { h2 = t; int flag = 0; while (h2 != NULL) { p = (node)malloc(sizeof(Node)); if (h1->next->id == h2->id) { p = h1->next; h1->next = p->next; free(p); flag = 1; } h2 = h2->next; } if(flag == 0) //重点! h1 = h1->next; //重点! } }
这里有一个重点,就是如果进行了删除,是不需要进行指向下一个链表的,
因为h1之前指向的next已经被删除了,现在指向的next应该是之前的next
的next,所以不需要再往后移动了
最后进行打印
void outPut(node h1) { int count = 0; node p = h1; while (h1 = h1->next) count++; printf("%d\n", count); p = p->next; while (p != NULL) { printf("%d %d\n", p->id, p->chengji); p = p->next; } }
参考代码:
#include <stdio.h> #include <malloc.h> typedef struct student { int id; int chengji; struct student* next; }*node, Node; node creat(int n) { node head, p, q; head = (node)malloc(sizeof(Node)); head->next = NULL; q = head; for (int i = 0; i < n; i++) { p = (node)malloc(sizeof(Node)); scanf("%d%d", &(*p).id, &p->chengji); p->next = q->next; q->next = p; q = p; } return head; } void fun(node h1, node h2) { h2 = h2->next; node p, t = h2; while (h1->next != NULL) { h2 = t; int flag = 0; while (h2 != NULL) { p = (node)malloc(sizeof(Node)); if (h1->next->id == h2->id) { p = h1->next; h1->next = p->next; free(p); flag = 1; } h2 = h2->next; } if(flag == 0) h1 = h1->next; } } void outPut(node h1) { int count = 0; node p = h1; while (h1 = h1->next) count++; printf("%d\n", count); p = p->next; while (p != NULL) { printf("%d %d\n", p->id, p->chengji); p = p->next; } } int main() { int m, n; node head1, head2; scanf("%d%d", &n, &m); head1 = creat(n); head2 = creat(m); fun(head1, head2); outPut(head1); return 0; }
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:821 |
简单的a+b (C语言代码)浏览:572 |
字符逆序 (C语言代码)浏览:675 |
C语言程序设计教程(第三版)课后习题7.4 (C语言代码)浏览:476 |
矩阵的对角线之和 (C语言代码)浏览:1401 |
C语言程序设计教程(第三版)课后习题8.1 (C语言代码)浏览:765 |
C语言程序设计教程(第三版)课后习题10.1 (C语言代码)浏览:826 |
字符删除 (C语言代码)浏览:767 |
简单的a+b (C语言代码)浏览:587 |
C语言程序设计教程(第三版)课后习题6.11 (C++代码)浏览:534 |