设计一个函数 void Intersection(List La, List Lb) , 其功能是求Lb和La的交集,且将交集的结果置于La中,其中La和Lb的元素均为严格递增有序排列,求交集后的La的元素也为严格递增有序排列。La和Lb是带头结点的单向链表。
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
| #include <stdio.h> #include <stdlib.h>
typedef struct T_Node { int d; struct T_Node* next; } Node, * List;
void Intersection(List La, List Lb) { Node* pre = La; Node* p1 = La->next; Node* p2 = Lb->next;
while (p1 != NULL && p2 != NULL) { if (p1->d == p2->d) { pre = p1; p1 = p1->next; p2 = p2->next; } else if (p1->d > p2->d) { do { p2 = p2->next; } while (p2 != NULL && p1->d > p2->d); } else { do { p1 = p1->next; free(pre->next); pre->next = p1; } while (p1 != NULL && p1->d < p2->d); } }
if (p1 != NULL) { do { p1 = p1->next; free(pre->next); pre->next = p1; } while (p1 != NULL); } }
void createlink(List* pla, List* plb) { int i; Node* p;
*pla = (Node*)malloc(sizeof(Node)); p = *pla;
for (i = 1; i <= 10; i++) { p->next = (Node*)malloc(sizeof(Node)); p = p->next; p->d = i * 2; p->next = NULL; }
*plb = (Node*)malloc(sizeof(Node)); p = *plb;
for (i = 1; i <= 8; i++) { p->next = (Node*)malloc(sizeof(Node)); p = p->next; p->d = i + 6; p->next = NULL; } }
void main() { int i;
List la, lb; Node* p;
createlink(&la, &lb); Intersection(la, lb); p = la->next; while (p != NULL) { printf("%4d", p->d); p = p->next; } printf("\n"); }
|