集合分可分為有序集合和無序集合,可以分別用有序鏈表和無序鏈表進行表示。
以下用有序鏈表表示有序集合。
- 集合的結構定義
1 /*鏈表中的結點定義*/ 2 typedef struct node 3 { 4 ListItem element; 5 link next; 6 }Node, *link; 7 8 /*集合定義*/ 9 typedef struct list 10 { 11 link frist; //指向第一個元素的指針 12 }List,*Set;
- 相關操作
1 /*創建一個空集合*/ 2 Set SetInit() 3 { 4 Set S = new List; 5 S->frist = NULL; 6 return S; 7 } 8 9 /*判斷一個集合是否為空*/ 10 int SetEmpty(Set S) 11 { 12 return S->frist == NULL; 13 } 14 15 /*SetSize(S)返回集合S的大小*/ 16 int SetSize(Set S) 17 { 18 int len; 19 link curren = S->frist; 20 len = 0; 21 while (curren) 22 { 23 len++; 24 curren = curren->next; 25 } 26 return len; 27 } 28 29 /*SetAssign(A,B)用集合B給集合A賦值,不能簡單的將A->first指向B的first指針指向單元*/ 30 void SetAssign(Set A, Set B) 31 { 32 link a, b, c; 33 b = B->frist; 34 A->frist = NULL; 35 if (b) 36 { 37 A->frist = new Node; 38 a = A->frist; 39 a->element = b->element; 40 a->next = NULL; 41 b = b->next; 42 } 43 while (b) 44 { 45 c = new Node; 46 c->element = b->element; 47 c->next = NULL; 48 b = b->next; 49 a->next = c; 50 a = c; 51 } 52 } 53 54 /*SetIntersection(A,B)通過遍歷集合A和B的鏈表來實現交集*/ 55 Set SetIntersection(Set A, Set B) 56 { 57 link a, b, p, q, r; 58 Set tmp = SetInit(); //創建一個臨時集合 59 a = A->frist; 60 b = B->frist; 61 p = new Node; 62 q = p; 63 while (a&&b) 64 { 65 if (a->element == b->element) 66 { 67 r = new Node; 68 r->element = a->element; 69 r->next = NULL; 70 p->next = r; 71 p = r; 72 a = a->next; 73 b = b->next; 74 } 75 else if (a->element < b->element) 76 a = a->next; 77 else 78 b = b->next; 79 } 80 if (p != q) //p==q,此時集合無交集 81 tmp->frist = q->next; 82 delete q; 83 return tmp; 84 } 85 86 /*SetInsert(x,S)將元素x插入到集合S中*/ 87 void SetInsert(ListItem x, Set S) 88 { 89 link p, q, r; 90 p = S->frist; 91 q = p; 92 while (p&&p->element<x) 93 { 94 q = p; 95 p = p->next; 96 } 97 if (p&&p->element == x) 98 return; 99 r = new Node(); 100 r->element = x; 101 r->next = p; 102 if (p == q) 103 S->frist = r; 104 else 105 q->next = r; 106 }
