原题链接:[编程入门]链表之节点删除
参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | #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 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复