参考代码如下:
#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 人评分
Pascal三角 (C语言代码)浏览:1252 |
众数问题 (C语言代码)浏览:911 |
WU-判定字符位置 (C++代码)浏览:1471 |
C语言程序设计教程(第三版)课后习题6.8 (C++代码)浏览:614 |
简单的a+b (C语言代码)浏览:529 |
JAM计数法 (C语言代码)浏览:721 |
C语言程序设计教程(第三版)课后习题11.1 (C语言代码)浏览:504 |
简单的a+b (C语言代码)浏览:617 |
汽水瓶 (C语言代码)浏览:579 |
1063题 初学者,求帮忙看下,不知道哪错了浏览:239 |