原题链接:[编程入门]链表之节点删除
参考代码如下:
#include <stdio.h> #include <stdlib.h> //定义一个学生结构体 typedef struct Student { int id; int score; struct Student *pNext; } STU, *PSTU; //创建一个长度为num的链表 PSTU create_list(int num) { PSTU pHead = (PSTU)malloc(sizeof(STU)); if (pHead == NULL) { perror("malloc error"); exit(-1); } pHead->pNext = NULL; PSTU pTail = pHead; PSTU pNew = NULL; int idtmp; int scoretmp; int i; for (i = 0; i < num; i++) { pNew = (PSTU)malloc(sizeof(STU)); if (pNew == NULL) { perror("malloc error"); exit(-1); } scanf("%d %d", &idtmp, &scoretmp); pNew->id = idtmp; pNew->score = scoretmp; pNew->pNext = NULL; pTail->pNext = pNew; pNew->pNext = NULL; pTail = pNew; } return pHead; } //打印链表 void print_list(PSTU pHead) { if (pHead == NULL || pHead->pNext == NULL) { printf("print_list error! the list is empty or not exit!\n"); return; } PSTU pCur = pHead->pNext; while (pCur != NULL) { printf("%d %d\n", pCur->id, pCur->score); pCur = pCur->pNext; } } //求链表长度 int list_len(PSTU pHead) { if (pHead == NULL) { printf("list_len error! the list is not exit!\n"); return -1; } int len = 0; PSTU pCur = pHead->pNext; while (pCur != NULL) { len++; pCur = pCur->pNext; } return len; } //从A链表中删去B链表中有相同学号的那些节点 void process(PSTU pHeadA, PSTU pHeadB) { PSTU pPreA = pHeadA; PSTU pCurA = pHeadA->pNext; PSTU pCurB = pHeadB->pNext; int flag; //定义一个标志位,判断是否删除了结点 while (pCurA != NULL) //遍历链表A中的每个结点 { flag = 0; //对于链表A的每个结点,都要遍历链表B中所有结点 while (pCurB != NULL) { if (pCurA->id == pCurB->id) { pPreA->pNext = pCurA->pNext; free(pCurA); //释放被删除结点的空间 pCurA = NULL; pCurA = pPreA->pNext; flag = 1; //把标志位置1 break; //跳出里面这个循环 } pCurB = pCurB->pNext; } pCurB = pHeadB->pNext; //下次查找继续从首结点开始遍历B链表 if (flag == 0) { pPreA = pPreA->pNext; pCurA = pCurA->pNext; } } } int main(void) { int n, m; scanf("%d %d", &n, &m); PSTU pHeadA = create_list(n); PSTU pHeadB = create_list(m); /* printf("list A: \n"); print_list(pHeadA); int lenA = list_len(pHeadA); printf("lenA = %d\n", lenA); printf("list B: \n"); print_list(pHeadB); int lenB = list_len(pHeadB); printf("lenB = %d\n", lenB); */ process(pHeadA, pHeadB); int lenA = list_len(pHeadA); printf("%d\n", lenA); print_list(pHeadA); return 0; }
0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复